VueJS 2,路由器后卫
问题描述:
我的指数途径定义为:VueJS 2,路由器后卫
{ path: '/', adminOnly: false, component: Main },
是否有访问“adminOnly”属性的方法吗?
有似乎没有在这个代码块这样的方式:
routes.beforeEach((to, from, next) => {
console.log(to)
next();
});
我的路线文件:
import Vue from 'vue';
import VueRouter from 'vue-router';
import Main from '../components/Main.vue';
import About from '../components/About.vue';
const NotFoundException = {
template: '<div>Route Was Not Found</div>'
};
Vue.use(VueRouter);
const routes = new VueRouter({
mode: 'history',
hashbang: false,
linkActiveClass: 'active',
base: '/jokes',
routes: [
{ path: '/', adminOnly: false, component: Main },
{ path: '/about', adminOnly: false, component: About },
{ path: '*', adminOnly: false, component: NotFoundException }
]
});
routes.mode = 'html5';
routes.beforeEach((to, from, next) => {
// CHECK IF ADMINONLY EXISTS
next();
});
export default routes;
我没有加入adminOnly.js的混入得到解决其中包含以下代码: 但是,如果我要将用户重定向到登录页面(如果不是管理员),则必须再次将mixin添加到每个组件。 //只是测试 var isAdmin = false;
export default {
beforeRouteEnter (to, from, next) {
if(!isAdmin) {
next((vm) => {
vm.$router.push('/login');
});
}
}
}
答
是的,有更好的方法来处理这个问题。每个路由对象可以有meta
字段。只是包装adminOnly
财产元对象:
routes: [
{ path: '/', meta: { adminOnly: false }, component: Main },
{ path: '/about', meta: { adminOnly: false }, component: About },
{ path: '*', meta: { adminOnly: false }, component: NotFoundException }
]
检查路线管理员权限:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.adminOnly)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
}
}
小例子你有一个错字:'纪录beforeEach()'钩子中的.meta.requiresAuth',在这种情况下应该是'record.meta.adminOnly'。 – branquito
请检查文档 –
在文档中,他们在元对象上有一个名为'requireAuth'的属性,而这里的OP问题使用'adminOnly'来代替,因此,您的钩子将无法工作。 – branquito