2017-01-10 347 views
4

我的指數途徑定義爲: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'); 
       }); 
      } 
     } 
    } 

回答

5

是的,有更好的方法來處理這個問題。每個路由對象可以有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

+0

小例子你有一個錯字:'紀錄beforeEach()'鉤子中的.meta.requiresAuth',在這種情況下應該是'record.meta.adminOnly'。 – branquito

+0

請檢查文檔 –

+0

在文檔中,他們在元對象上有一個名爲'requireAuth'的屬性,而這裏的OP問題使用'adminOnly'來代替,因此,您的鉤子將無法工作。 – branquito