Nuxt中使用localStorage
nuxt中使用直接使用localStorage会报错,localStorage is not defined
由于nuxt是服务端渲染框架,所以页面会先在服务端执行,并返回给客户端展示,但是localStorage是客户端缓存,在ssr的服务端渲染时执行会报错如下:
所以有以下几种解决方法
方法一:写在onmounted里面
方法二:新建composables(注意文件夹名字要用这个不能改)文件夹,自己封装方法放在composables里面,nuxt3中,写在composables文件夹下面的方法会自动导入,可全局使用而不需要使用的时候再单独使用
a)在composables(注意全局方法文件一定要放这个文件夹下)文件夹下新建localstorage.ts
b)在要使用的地方如app.vue的script中调用方法
方法三:判断process.client
方法四:为了保持和原来使用localstorage的使用体验一致,也可以按照如下写法:
以下是localStorage常用方法的封装:
export const localSorage = {
setItem:(key:string,val:any)=>{
if(process.client){
localStorage.setItem(key,JSON.stringify(val))
}
},
getItem:(key:string)=>{
if(process.client){
return localStorage.getItem(key)
}
},
removeItem:(key:string)=>{
if(process.client){
return localStorage.removeItem(key)
}
},
clear:()=>{
if(process.client){
return localStorage.clear()
}
},
key:(index:number)=>{
if(process.client){
return localStorage.key(index)
}
},
// 尽量保持和原来的用法一致
length:process.client?localStorage.length:0
}
更多推荐
所有评论(0)