使用vuex存储用户信息到localStorage

1、首先需要装vuex

1 # NPM
2 npm install vuex --save
3 # Yarn
4 yarn add vuex

网址:https://vuex.vuejs.org/installation.html
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,由于localStrory的特性,所以每次登录前或者退出后要清除缓存

登录前清除,一般放在created或者mouted里
created(){
      window.localStorage.clear()
    },
退出后一般放在销毁函数里

ps:

state 里的值一定是null,如果是空的话,会判断为true,会出错
 
posted @ 2018-12-25 10:44  Ms-Hibiscus  阅读(2191)  评论(0编辑  收藏  举报