gpt4 book ai didi

javascript - 如何在 Nuxt.js 存储中使用 localStorage

转载 作者:行者123 更新时间:2023-11-30 13:51:28 25 4
gpt4 key购买 nike

我正在做一个 nuxt.js 项目。在这里,我想在 Nuxt-Store 中使用 localStorage 并且还想访问 localStorage 来自 Nuxt-Middleware 的值。它显示错误。

localStorage is not defined.

我该如何解决这个问题?

这里是store/index.js的代码示例

setUser(state, { user }){
state.user = user
state.isLoggedIn = true
localStorage.setItem('user', JSON.stringify(user));
localStorage.setItem('isLoggedIn', state.isLoggedIn);
},

我的中间件代码在这里-

export default function({ store, redirect, route}) {
const user = localStorage.getItem('user');
const loggedStatus = store.getters['isLoggedIn']

if (user) {
if(route.path == '/login' || route.path == '/user/temporary'){
return redirect('/')
}
return
}


if(!user){
return redirect('/login')
}

}

最佳答案

为了在客户端运行此代码,您需要向中间件添加一些逻辑。检查docs阅读更多。

In universal mode, middlewares will be called server-side once (on the first request to the Nuxt app or when page refreshes) and client-side when navigating to further routes. In SPA mode, middlewares will be called client-side on the first request and when navigating to further routes.

将以下内容添加到您的中间件函数中:

export default function({ store, redirect, route }) {

// Do not run on server
if (process.server) {
return
}

const user = localStorage.getItem('user')
const loggedStatus = store.getters['isLoggedIn']

if (user) {
if (route.path == '/login' || route.path == '/user/temporary') {
return redirect('/')
}
return
}

if (!user) {
return redirect('/login')
}
}

如果您在 SPA 模式下运行,那么您就完成了。此中间件将仅在每次加载、初始加载和页面间导航时在客户端上运行。

现在,如果您在通用模式下运行,这个中间件将不再在服务器上运行,但它也不会在第一个应用程序加载时运行。

In universal mode, middlewares will be called server-side once (on the first request to the Nuxt app or when page refreshes) and client-side when navigating to further routes

解决此问题的最简单方法是同时添加一个仅在客户端上运行的插件。取自this问题,将此插件添加到您的 nuxt.config.js,注意添加 .client 后缀:

// nuxt.config.js
export default {
plugins: [
// .client will only be run client side on initial app load
'~/plugins/init.client.js'
]
}

在这个插件中,您可以定义与您的中间件相同的逻辑:

// /plugins/init.client.js
export default function({ store, redirect, route }) {

const user = localStorage.getItem('user')
const loggedStatus = store.getters['isLoggedIn']

if (user) {
if (route.path == '/login' || route.path == '/user/temporary') {
return redirect('/')
}
return
}

if (!user) {
return redirect('/login')
}
}

此示例与 DRY 原则背道而驰,旨在作为解决 Nuxt 中间件限制的示例。

希望这对您有所帮助!

关于javascript - 如何在 Nuxt.js 存储中使用 localStorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58153979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com