赞
踩
config>index.js中:
- // localStorage的二次封装
- import config from "../config";
-
- export default {
- setItem(key,val){
- // 2、增加值
- let storage = this.getStroage();
- storage[key] = val;
- // 3、让命名空间重新生效(为了避免和其它项目有冲突,所以有命名空间)
- window.localStorage.setItem(config.namespace,JSON.stringify(storage));
- },
- getItem(key){
- return this.getStroage()[key]
- },
- getStroage(){
- // 1、首先获取此命名空间下的值,并转换成对象
- return JSON.parse(window.localStorage.getItem(config.namespace) || "{}");
- },
- clearItem(key){
- // 4、清除
- let storage = this.getStroage()
- delete storage[key]
- window.localStorage.setItem(config.namespace,JSON.stringify(storage));
- },
- clearAll(){
- // 5、清除所有
- window.localStorage.clear()
- }
- }

(全局注册)
- import storage from './utils/storage'
-
- const app = createApp(App)
- // 全局注册
- app.config.globalProperties.$storage = storage
Login.vue中添加字段
- mounted() {
- // 需要先挂载,再能调用
- this.$storage.setItem('user', { name: "张三", age: 18})
- }
存储结果:
manage是设置的命名空间,这样就可以避免和其它项目冲突的问题
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。