我有一个命名的视图路由:
let routes = [
{
name: "home",
path: '/',
components: {
default: Home,
project: 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
时显示settings_button
组件,而不是在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>
您只需检查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();
}
}
如果您有 2 个具有相同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 }
})