使用vuex存储用户信息到localStorage的实例
更新时间:2019年11月11日 15:46:21 作者:guoxq~
今天小编就为大家分享一篇使用vuex存储用户信息到localStorage的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
1、首先需要装vuex
npm install vuex -d
2、新建store文件夹,新建index.js, 并引入vue、vuex,代码如下:
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const key = 'user' const store = new Vuex.Store({ state () { return { user: null } }, getters: { getStorage: function (state) { if (!state.user) { state.user = JSON.parse(localStorage.getItem(key)) } return state.user } }, mutations: { $_setStorage (state, value) { state.user = value localStorage.setItem(key, JSON.stringify(value)) }, $_removeStorage (state) { state.user = null localStorage.removeItem(key) } } }) export default store
3、在main.js中引入store,
import store from './store/index' new Vue({ el: '#app', router, store, // 引入store components: { App }, template: '<App/>' })
4、在登录组件中,如代码所示:
this.$message({ message: '登录成功', type: 'success' }) this.$store.commit('$_setStorage', {user: this.loginForm.username}) this.$router.push({name: 'Home'})
5、储存其他状态类信息,方式相同。
以上这篇使用vuex存储用户信息到localStorage的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
解决vue-router进行build无法正常显示路由页面的问题
下面小编就为大家分享一篇解决vue-router进行build无法正常显示路由页面的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2018-03-03解决router.beforeEach()动态加载路由出现死循环问题
这篇文章主要介绍了解决router.beforeEach()动态加载路由出现死循环问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-10-10利用Vue.js+Node.js+MongoDB实现一个博客系统(附源码)
本文主要介绍了利用Vue.js+Node.js+MongoDB实现一个博客系统,这个博客使用Vue做前端框架,Node+express做后端,数据库使用的是MongoDB。实现了用户注册、用户登录、博客管理、文章编辑、标签分类等功能,需要的朋友可以参考学习。2017-04-04
最新评论