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,會出錯