Vue.js 当用户登录时,如何禁用对登录和注册页面的访问?
我不明白为什么这不起作用 路线Vue.js 当用户登录时,如何禁用对登录和注册页面的访问?,vue.js,vue-router,Vue.js,Vue Router,我不明白为什么这不起作用 路线 const router = new VueRouter({ mode: 'history', routes: [ { path: '/', component: Home, name: 'Home', meta: { requiresAuth: true }}, { path: '/adminarea', component: Admin, name:"Admin", meta: { requiresAuth: true }},
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/', component: Home, name: 'Home', meta: { requiresAuth: true }},
{ path: '/adminarea', component: Admin, name:"Admin", meta: { requiresAuth: true }},
{ path: '/login', component: Login, name: 'Login'},
{ path: '/signup', component: Register, name: 'Signup'},
]
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!store.getters.getAuth) {
next({ name: 'Login' })
} else {
next();
}
} else {
next()
}
}))
to.matched.some(record=>record.meta.requiresAuth此行应该只允许带有meta requiresAuth的路由,但我不知道为什么它还允许其他路由
我可以手动访问登录和注册页面。
我想不出这里出了什么问题。我在路由器元部分中包含了一个
disableIfLoggedIn
值
{
name: 'login',
path: '/login',
component: Login,
meta: {
disableIfLoggedIn: true
}
},
每次路线导航前都会进行检查
import {store} from "./store"; // import the store to check if authenticated
router.beforeEach((to, from, next) => {
// if the route is not public
if (!to.meta.public) {
// if the user authenticated
if (store.getters.isAuthenticated) { // I declared a `getter` function in the store to check if the user is authenticated.
// continue to the route
next();
} else {
// redirect to login
next({name: 'login'});
}
}
next();
});
在存储
中声明一个getter
函数,以检查是否经过身份验证
const getters = {
isAuthenticated: state => {
return state.isAuth; // code to check if authenticated
}
};
元值disableIfLoggedIn
可以在任何路由器对象中设置为true。登录后将无法访问