javascript – 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: '/',{ path: '/about',component: About },{ path: '*',component: NotFoundException }
    ]
});
routes.mode = 'html5';

routes.beforeEach((to,next) => {
    // CHECK IF ADMINONLY EXISTS
    next();
});

export default routes;

我确实通过添加一个adminOnly.js的混合物来获得解决方案,其中包含以下代码
但是,如果我要将用户重定向登录页面(如果不是管理员),则必须将mixin添加到每个组件中.
//只是一个测试
var isAdmin = false;

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

解决方法

是的,有更好的方法来处理这个问题.每个路由对象都可以有元字段.只需在Meta对象中包装adminOnly属性
routes: [
        { path: '/',Meta: { adminOnly: false },component: NotFoundException }
    ]

检查管理员权限的路线:

router.beforeEach((to,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创建了一些示例

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...