最近在做登錄得時候用到了vuex中的plugins.js插件。發現挺好用,可以推薦大家使用以下
使用方法得話,我用的比較簡單首先在store文件中創建一個plugins.js文件夾。
內容如下
const plugin = store => {
let arr = Object.keys(store.state);
let obj = {};
arr.forEach(item => {
if (window.localStorage[item]) {
obj[item] = JSON.parse(window.localStorage[item]);
store.replaceState(obj);
}
});
// 當 store 初始化后調用
store.subscribe((mutation, state) => {
// 每次 mutation 之后調用
// mutation 的格式為 { type, payload }
// console.log(arr);
if (state.agreed == false) {
localStorage.removeItem("login");
window.sessionStorage.setItem("login", JSON.stringify(state.login));
// arr.forEach(item => {
// window.localStorage.clear();
// window.sessionStorage[item] = JSON.stringify(state[item]);
// });
} else if (state.agreed == true) {
sessionStorage.removeItem("login");
window.localStorage.setItem("login", JSON.stringify(state.login));
// arr.forEach(item => {
// window.sessionStorage.clear();
// window.localStorage[item] = JSON.stringify(state[item]);
// });
}
});
};
export default plugin;
具體得話按照自己得方式來
寫好之后再在store文件中的index.js中引用即可
plugins: [plugin]。
自我總結,它是一個長期存儲得解決方法,因為放在state中的數據在刷新時會丟失,這時候使用這個plugin.js插件它會幫你存儲起來。
以前存儲token都是直接用得localstorage,這次用了新的方式總結一下。
