访问中间件中的LocalStorage-NuxtJs [英] Access LocalStorage in Middleware - NuxtJs
问题描述
好吧,我从nuxt开始,我有以下路线:
Well, I'm starting with nuxt and I have following routes:
/home
/dashboard
/login
我想保护/dashboard,但仅适用于使用localStorage
中的令牌登录的用户.
I want to protect the /dashboard, but only for users logged in with a token in localStorage
.
我想到的最简单的方法是创建一个/middleware/auth.js
The simplest way I thought of doing this was by creating a /middleware/auth.js
export default function () {
if (!window.localStorage.getItem('token')) {
window.location = '/login'
}
}
并将其注册到/dashboard/index.vue组件中.
and registering it in the /dashboard/index.vue component.
<script>
export default {
middleware: 'auth',
}
</script>
但是我无法在中间件中访问localStorage
,因为LocalStorage是客户端.
But I cannot access localStorage
within a middleware, because LocalStorage is client-side.
我已经尝试过在created()
仪表板布局中添加相同的检查,但是我无法返回未设置的窗口mounted()
为时已晚,它只能在页面完全组装后进行检查.
I have already tried to add this same check in the created()
dashboard layout, but I cannot return window not set mounted()
is too late, it can only check after the page has been fully assembled.
那么我该如何实现呢? 注意:我不打算在该项目中使用任何Vuex.
So how can I achieve this? Note: I do not intend to use any Vuex for this project.
推荐答案
在vuex存储上进行登录操作,我设置了带有令牌的提交
on vuex store for login action i set a commit with the token
window.$nuxt.$cookies.set('token', payload, {
path: '/',
})
middleware/auth.js
middleware/auth.js
export default (context) => {
if (!context.app.context.app.$cookies.get('token')) {
return context.redirect('/login')
}
}
这篇关于访问中间件中的LocalStorage-NuxtJs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!