我从我的 middleware/auth.js
中截取了以下代码,如果用户未经身份验证,它会将用户重定向到登录页面。
export default function ({ store, redirect }) {
if (!store.state.admin.isAdmin) {
redirect('/auth/login')
}
}
现在我想禁止经过身份验证的用户访问登录页面并在他们点击登录 url 时重定向到 ('/manage/dashboard')。
我在登录 View 中使用了以下方法:
mounted () {
if (localStorage.getItem('token') && localStorage.getItem('userId')) {
this.$router.replace({ path: '/admin/dashboard' })
}
}
这可行,但执行速度太慢,用户只能看到登录页面几秒钟。
实现重定向的有效方法是什么?
最佳答案
我不会从登录 View 访问 localStorage,我更愿意在您的商店中设置它然后访问商店。我没有运行这段代码,但我想你想做这样的事情。
您可以创建另一个 check-auth.js 中间件并将其添加到您的登录 View 。
检查auth.js
export default function (context) {
context.store.dispatch('initAuth', context.req);
}
商店/index.js
state:{
authenticated:false;
}
mutations: {
setAuthentication(state, auth) {
state.authenticated = auth;
},
}
actions: {
initAuth(vuexContext, req) {
if (localStorage.getItem('token') && localStorage.getItem('userId')){
vuexContext.commit('setAuthentication', true);
}else{
vuexContext.commit('setAuthentication', false);
}
}
},
getters: {
isAuthenticated(state) {
return state.authenticated;
},
},
然后检查用户是否通过身份验证 auth.js
if (!context.store.getters.isAuthenticated) {
context.redirect('/auth/login');
}
将中间件添加到您的 View
export default {
middleware: ['check-auth', 'auth'],
components: {},
methods: {},
};
关于javascript - 禁止经过身份验证的用户访问nuxt js中的登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64099365/