首页 > 解决方案 > 在命名视图路由器下仅保护一个组件 - Vue js

问题描述

我有一个命名的视图路线:

let routes = [
    {
        name: "home",
        path: '/',
        components: {
            default: Home,
            project: ProjectIndex
        }
    }
]

我想根据用户角色保护“项目”路线,但任何人都需要可以访问默认主页。

我将此添加到 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)得到了路线,但没有告诉我将呈现哪个组件。我在这里碰壁了。请帮忙。

标签: javascriptvue.jsbabeljsvue-router

解决方案


我将向您展示如何支持延迟加载。

//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 } 

并且您想settings_button在用户是admin而不是何时显示组件visitor

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>

推荐阅读