vue项目持久化存储数据的实现代码

方式一、使用localStorage在数据存储

1、要在浏览器刷新的时候重新存储起来

if (window.localStorage.getItem(authToken)) {
store.commit(types.SETLOANNUMBER, window.localStorage.getItem('loanNumber'));
}

方式二、使用vue-cookie插件来做存储

1、参考地址传送门

2、安装包

npm install vue-cookie --save

3、在store中存储起来

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex)
var VueCookie = require('vue-cookie');

export default new Vuex.Store({
state: {
token: VueCookie.get('token')
},
mutations: {
saveToken(state, token) {
state.token = token;
// 设置存储
VueCookie.set('token', token, { expires: '30s' });
}
},
actions: {

}
})

4、在登录页面中设置到存储中

import { mapMutations } from 'vuex';
export default {
methods: {
login() {
this.saveToken('123')
},
...mapMutations(['saveToken'])
}
};

方式三、使用vuex-persistedstate插件参考文件

在做大型项目,很多数据需要存储的建议使用这种方式

您可能感兴趣的文章:

文章同步发布: https://www.geek-share.com/detail/2756840369.html

原文地址:https://www.cnblogs.com/xxcn/p/10188578.html