【问题标题】:VueJS 2, router guardVueJS 2,路由器保护
【发布时间】:2017-01-10 01:34:25
【问题描述】:

我的索引路由定义为:

{ 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 获得了解决方案,其中包含以下代码: 但是话又说回来,如果我要将用户重定向到登录页面(如果不是管理员),则必须将 mixin 添加到每个组件中。 //只是一个测试 var isAdmin = false;

export default {
        beforeRouteEnter (to, from, next) {
            if(!isAdmin) {
                next((vm) => {
                   vm.$router.push('/login');
                });
            }
        }
    }

【问题讨论】:

    标签: javascript vuejs2 vue-router


    【解决方案1】:

    是的,有更好的方法来处理这个问题。每个路由对象都可以有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.
      }
    }
    

    更多信息请查看docs,我在jsFiddle上创建了一个小例子

    【讨论】:

    • 你有一个错字:record.meta.requiresAuth in beforeEach() hook,在这种情况下应该是 record.meta.adminOnly
    • 在文档中,他们在元对象上有一个名为 requiresAuth 的属性,而此处的 OP 问题使用 adminOnly 代替,因此,您的钩子将无法正常工作。
    猜你喜欢
    • 1970-01-01
    • 2020-02-08
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多