首页 > 编程 > JavaScript > 正文

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

2019-11-19 12:47:57
字体:
来源:转载
供稿:网友

方式一、使用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插件参考文件

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表