Vue不能實(shí)時(shí)監(jiān)控LocalStorge中的數(shù)據(jù),當(dāng)需要在組件間共享狀態(tài)時(shí)無法實(shí)現(xiàn)良好的效果。
Vuex是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化。
1.安裝
利用npm安裝Vuex
npm install vuex --save
在src下新建store文件夾,并在其中新建stroe.js中顯式地通過 Vue.use() 來加載Vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
2.使用vuex配合路由守衛(wèi)實(shí)現(xiàn)過濾器效果
在前置頁面中添加list_view的標(biāo)識,在后置頁面中判斷標(biāo)識是否存在,如果存在就可以進(jìn)入,不存在則直接將url重置為首頁。
在store.js中設(shè)置本地存儲標(biāo)識list_view,并聲明mutation:in_list完成list_view的賦值
export default new Vuex.Store({
state: {
list_view: ''
},
mutations: {
in_list: (state, n) => {
let list_view = JSON.parse(n);
sessionStorage.setItem('list_view', JSON.stringify(list_view));
state.list_view = list_view;
}
}
})
在前置頁面的代碼中添加代碼
this.$store.commit('in_list',true);
在后置頁面中添加beforeRouteEnter事件中處理。
beforeRouteEnter: (to,from,next) => {
var s = JSON.parse(sessionStorage.getItem('list_view'));
if(s){
next();
}else{
next("/");
}
}
3.vuex,sessionStorage,localStorage的區(qū)別
vuex中的數(shù)據(jù)是保存在Vue原型對象中,頁面刷新時(shí)Vue原型對象會重建,vuex中數(shù)據(jù)丟失
sessionStorage中的數(shù)據(jù)保存在瀏覽器頁面內(nèi)存中(本選卡內(nèi)),刷新頁面不會丟失,但切換選項(xiàng)卡或關(guān)閉瀏覽器會丟失
localStorage中的數(shù)據(jù)保存在本地,時(shí)間較長,直至清除時(shí)丟失