使用vuex存储用户信息到localStorage的实例

发布时间:2020-08-22 23:03:49 作者:guoxq~
来源:脚本之家 阅读:302

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的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

推荐阅读:
  1. localstorage存储对象数组
  2. localStorage存储读取JSON如何实现

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vuex 存储 localstorage

上一篇:全面解析jQuery中的$(window)与$(document)的用法区别

下一篇:vue3.0中的双向数据绑定方法及优缺点

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》