[英]Guard for only one component under named view router - Vue js
我有一個命名視圖路線:
let routes = [
{
name: "home",
path: '/',
components: {
default: Home,
project: ProjectIndex
}
}
]
我想基於用戶角色來保護“項目”路由,但是任何人都必須可以訪問默認的Home。
我將其添加到ProjectIndex組件:
beforeRouteEnter (to, from, next) {
var user = Spark.state.user;
if(user.current_role == 'admin' || user.current_role == 'owner'){
next();
}
}
但是路由器也在Home組件上執行此代碼,因此Home也受此影響。
我不認為在Vue js中這么簡單的事情應該這么難。
如果我console.log(to)
我得到路由,但沒有任何信息告訴我將要渲染哪個組件。 我在這里撞牆。 請幫忙。
我將向您展示如何支持延遲加載。
//this function will do the check and import the component supporting lazy loading
//if the check does not fulfilled then the component will not imported
function check_condition(name_component) {
if (name_component === 'Project') {
const user = store.state.user
if (user.current_role == 'admin' || user.current_role == 'owner') {
return () => import(`@/components/${name_component}.vue`)
}
return
}
return () => import(`@/components/${name_component}.vue`)
}
export default new Router({
routes: [
{
path: '/',
name: 'home',
components: {
default: check_condition('Home'),
project: check_condition('Project')
}
},
{
path: '/about',
name: 'about',
component: check_condition('About')
}
]
})
我喜歡上面的方法,盡管當然還有其他方法。 如果您不喜歡上面的方法,或者它不適合您的問題,則可以嘗試以下方法。
假設您擁有的是vuex商店狀態:
state: { user: 'admin' //or visitor }
並且您想在用戶為admin
而不是visitor
時顯示settings_button
組件:
computed: {
should_show_settings_button () {
return this.$store.state.user === 'admin'
}
}
<template v-if="should_show_settings_button">
<router-view name="settings_button"></router-view>
</template>
你可以簡單地檢查to
網址:
beforeRouteEnter (to, from, next) {
if(to.pathname !== '/') {
//yours check
}
else {
next();
}
}
或更復雜的方法是每次檢查路由數組。 然后,您可以按組件名稱進行檢查。
let routesObjects = routes.reduce((obj, route) => { obj[route.path] = route.name; return obj; }, {});
beforeRouteEnter (to, from, next) {
let path = to.pathname;
if(routesObjects.hasOwnProperty(to) && routesObjects[to] !== 'home') {
//yours check
}
else {
next();
}
}
如果您有兩個具有相同pathnam
組件,則可以組合一個beforeEach
鈎子和meta
在您的組件中設置meta
標簽
routes: [
{ name: 'home', path: '/', meta: { isHome: true } }
]
然后檢查一下
router.beforeEach((to, from, next) => {
if(to.meta.isHome !== undefined && to.meta.isHome) { next(); }
else { //your check }
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.