Javascript 在vuejs中保护儿童路线
我试图从父路由保护子路由,但失败Javascript 在vuejs中保护儿童路线,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,我试图从父路由保护子路由,但失败 export default new Router({ routes: [ //frontend routes { {path: 'auth', component: Auth, children: authroutes, beforeEnter: (to, from, next) => { // check if user is a guest or loggedin
export default new Router({
routes: [
//frontend routes
{
{path: 'auth', component: Auth, children: authroutes,
beforeEnter: (to, from, next) => {
// check if user is a guest or loggedin
auth.canAccess(permissions.is_guest)
.then((res) => {
if (res.data.status) {
next();
} else {
router.push('/auth/not-allowed');
}
})
}}
]
}
]
})
现在在我的孩子路线上
authroutes.js
const authroutes = [
{path: '', redirect: 'login'},
{path: 'login', component: Login, name: "login" },
];
但是,当我将上面的beforeenter放在子路由上时,它可以工作,但会导致大量代码重复
我如何保护孩子不受父路由的影响
例如:guard/auth/login和
/auth/register
只需对要保护的字段使用路由的元字段,如下所示:
const authroutes = [
{path: '', redirect: 'login', meta: {requiresAuth: true}},
{path: 'login', component: Login, name: "login" , meta: {requiresAuth: true}},,
];
is_user_logged: () => !!localStorage.getItem('token')
然后配置路由器以检查路由是否具有指定的元字段,并执行重定向逻辑
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
auth.canAccess(permissions.is_guest)
.then((res) => {
if (res.data.status) {
next();
} else {
next('/auth/not-allowed');
}
})
}else {
next() // make sure to always call next()!
}
});
请在此处查看更多信息:只需使用route的元字段作为要保护的字段,如下所示:
const authroutes = [
{path: '', redirect: 'login', meta: {requiresAuth: true}},
{path: 'login', component: Login, name: "login" , meta: {requiresAuth: true}},,
];
is_user_logged: () => !!localStorage.getItem('token')
然后配置路由器以检查路由是否具有指定的元字段,并执行重定向逻辑
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
auth.canAccess(permissions.is_guest)
.then((res) => {
if (res.data.status) {
next();
} else {
next('/auth/not-allowed');
}
})
}else {
next() // make sure to always call next()!
}
});
请在此处查看更多信息:
还有一种方法:
请注意,is\u user\u logged()
这是一个检查用户是否已登录的函数。我更喜欢这样做:
const authroutes = [
{path: '', redirect: 'login', meta: {requiresAuth: true}},
{path: 'login', component: Login, name: "login" , meta: {requiresAuth: true}},,
];
is_user_logged: () => !!localStorage.getItem('token')
还有一种方法:
请注意,is\u user\u logged()
这是一个检查用户是否已登录的函数。我更喜欢这样做:
const authroutes = [
{path: '', redirect: 'login', meta: {requiresAuth: true}},
{path: 'login', component: Login, name: "login" , meta: {requiresAuth: true}},,
];
is_user_logged: () => !!localStorage.getItem('token')
@GEOFFREYMWANGI是
auth.canAccess(permissions.is_guest)
到服务器或数据库的异步方法?它是一种异步方法,返回承诺,从服务器中的数据库检查到使用mysql的php服务器db@GEOFFREYMWANGIisauth.canAccess(permissions.is\u guest)
服务器或数据库的异步方法?它是一种异步方法,返回一个承诺,从服务器中的数据库检查到一个带有mysql数据库的php服务器