需求:vue项目需要将登录信息保存为全局变量

window.localStorage

最开始是使用window.localstorage来进行存取登录信息,方法如下

封装了一个专门使用window.localStorage的js,需要时引入这个filter.js就行

js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
};

js
1
2
3
4
//使用
import filter from '../../common/util/filter';
this.partnerId = filter.getLocalStore('partnerId') || '';
filter.setLocalStore('userName', busiDataResp.userName);

但由于将用户信息存储在localStorage中不安全,这里修改为存储为全局变量的方式

简易版可读写的全局变量

plaintext
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//在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,使用的上面this.$root方法,之前商城系统使用的Vuex进行全局变量和全局方法的存储

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化

https://vuex.vuejs.org/zh/