关于nuxt store中保存localstorage的问题
作者:慕水渔
这篇文章主要介绍了关于nuxt store中保存localstorage的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
nuxt store中保存localstorage
一、如果是用Nuxtjs,请配置插件:
plugins:[
{src:'~/plugins/localstorage.js",ssr:false }
]然后,在localStorage.js中:
import createpersistedstate from "vuex-persistedstate';
impont * as Cookies from "js-cookie";
let cookiestorage ={
getItem: function(key){
return Cookies.getJSON(key);
},
setItem:function(key,value){
return cookies.set(key,value,{expires:3, secure:false});
},
removeItem:function(key){
return cookies.remove(key);
}
};
export default(context)>{
createpersistedState({
storage:cookiestorage,
BetState:cookiestorage.getItem,
setstate:cookiestorage.setItem
})(context.store);
};二、Nuxtjs的fetch只用于store,不能用来设置数据,可以用AsyncData设置教据,用在路由页面即可
三、fetch官方文档很清楚了:服务端或切换至目标路由之前
四、可以用nuxtServerInit+express session存储用户登录
nuxt监听本地存储localStorage
在 plugins文件夹的 util.js 里面写公共的方法,如下:
function dispatchEventStroage() {
const signSetItem = localStorage.setItem
localStorage.setItem = function(key, val) {
let setEvent = new Event('setItemEvent')
setEvent.key = key
setEvent.newValue = val
window.dispatchEvent(setEvent)
signSetItem.apply(this, arguments)
}
}
export default dispatchEventStroage;在需要监听的页面写,如下:
mounted() {
let _this = this;
//根据自己需要来监听对应的key
window.addEventListener("setItemEvent",function(e){
//e.key : 是值发生变化的key
//e.newValue : 是可以对应的新值
if(e.key==="l_QYCN"){
console.log('这里监听的本地存储>>>>>>',e.newValue);
_this.localLogin = e.newValue;
}
})
},总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
