需求:vue项目需要将登录信息保存为全局变量
window.localStorage
最开始是使用window.localstorage来进行存取登录信息,方法如下
封装了一个专门使用window.localStorage的js,需要时引入这个filter.js就行
const setLocalStore = (name, content) => {
if (!name) return
if (typeof content !== 'string') {
//window.localStorage只能存储字符串
content = JSON.stringify(content)
}
window.localStorage.setItem(name, content)
}
const getLocalStore = name => {
let result;
if(!name) {
result = '';
}else{
result = window.localStorage.getItem(name);
}
return result;
}
const removeLocalStore = name => {
if (!name) return
window.localStorage.removeItem(name)
}
const clearLocalStore = () => {
window.localStorage.clear();
}
export default {
setLocalStore,
getLocalStore,
removeLocalStore,
clearLocalStore
};
//使用
import filter from '../../common/util/filter';
this.partnerId = filter.getLocalStore('partnerId') || '';
filter.setLocalStore('userName', busiDataResp.userName);
但由于将用户信息存储在localStorage中不安全,这里修改为存储为全局变量的方式
简易版可读写的全局变量
//在main.js中定义,通过this.$root存取
new Vue({
data: function(){
return {
userName: ''
}
},
render: h=>h(App)
}).mount('#app');
//模板页面存取
this.$root.userName = "zhsi";
let userName = this.$root.userName;
Vuex
由于系统不大,未引用Vuex,之前商城系统使用的Vuex进行全局变量和全局方法的存储
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化
https://vuex.vuejs.org/zh/
我的博客主页 :https://qingmuzhang.gitee.io/