当前位置:网站首页>问题系列-如何修改或更新localhost里的值
问题系列-如何修改或更新localhost里的值
2022-08-09 12:52:00 【文默】
一、问题
背景
这次遇到的一个问题是我需要更改在登录后把后台返回给我的,我保存在localhost里的user信息,因为在我的项目中,我是通过该信息里的adminSchool来判断该管理员所属的学校的,一开始还好,但后面可客户添加需求了,需要有一个超级管理员能查看所有学校的信息,这时我就想偷懒了,预想给一个下拉框让他选择不同的学校,获取到不同的学校id就能直接使用前面的代码了,哈哈哈。
问题
在这里就有个问题了,如何修改localhost里的值,一开始我以为可以直接修改,就有了下面的写法(内心已经觉得不行的,死马但当马医了~~)

接着查了下资料,发现localstorage只能存字符串,直接改值肯定不行的呀~~
就去菜鸟查看了下localhost 如何增删改查,具体我就不说了,链接里有详细,我就不复述了。这里说三点就是
- 增/改用(setItem( “key” , “value” ))【key相同就会覆盖,不同就添加新的】
- 删用(removeItem( “key” , “value” ))
- JSON.parse()/JSON.stringify()前者字符串转变为json格式,后者json格式变为字符串格式
到这里我就发现改不了,我要改的是实际上是一个字符串,没办法获取到adminSchoo并且修改它的值为我要的。于是只能用个蠢办法了,我先读取到这个值,还原为json格式,修改后再保存回去,因为同名会覆盖之前的。
解决思路
- 先拿到 storage 然后用JSON.parse转 修改后用JSON.stringify再转 最后存进去
具体方法如下
//获取到选择学校的ID
handleCommand(response) {
console.log(response);
//获取到之前的user并且还原为json,暂存到userMassage(userMassage创建在data里面)
this.userMassage = JSON.parse(window.localStorage.getItem('user'));
console.log(this.userMassage);
//修改我要修改的adminSchool
this.userMassage.admin.adminSchool = response;
//把更新好的user,变为字符串形式
let user = JSON.stringify(this.userMassage)
//把user保存到localhost,因为与之前的同名,会覆盖之前的
window.localStorage.setItem("user" , user)
}
总结
这里搞明白localhost实际保存的是字符串就很好明白了,也不知道还有没有别的简便方法了,有的话非常感谢您的告知。非常感谢噢!!
边栏推荐
猜你喜欢

WSA toolkit installed app store tip doesn't work how to solve?

乐东消防救援大队应邀为干部开展消防安全培训

GIN Bind mode to get parameters and form validation

Flutter Getting Started and Advanced Tour (8) Button Widget

Flutter entry and advanced tour (6) Layout Widget

npm install失败

The sword refers to the offer, cuts the rope 2

为什么文字不贴合边

Oracle Recovery Tools修复空闲坏块

从NPU-SLAM-EDA技术分析
随机推荐
卷积神经网络表征可视化研究综述(1)
OOM排查和处理
[FPGA Tutorial Case 48] Image Case 8 - Realization of Converting RGB Image to HSV Image Based on FPGA, Assisted Verification by MATLAB
激光熔覆在农机修复强化中的应用及研究方向
How to save Simulink simulation model as image or PDF
Introduction to Flutter advanced trip Dialog&Toast (10)
LnReader编译
Bitmaps and bit operations
leetcode 20. Valid Parentheses 有效的括号(中等)
19、学习MySQL 索引
NFS pays special attention to the problem of permissions
GIN Bind模式获取参数和表单验证
Ledong Fire Rescue Brigade was invited to carry out fire safety training for cadres
Dry+Bean+Dataset R语言数据分析,报告英文
Data Mining-06
Anta and Huawei Sports Health jointly verify the champion running shoes and lead Chinese sports with innovation
GET POST PUT DELETE request in GIN
FPGA中串口通信的时钟频率和波特率计数
How to reduce the size of desktop icons after the computer is reinstalled
5G China unicom repeater network management protocol real-time requirements