我有一个命名视图路由:
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),我得到了路由,但没有告诉我哪个组件将被呈现。我在这里碰壁了。请帮帮忙。
发布于 2018-06-23 02:41:45
,我也会向你展示如何支持延迟加载。
//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')
}
]
})我喜欢上面的approach.Though,当然还有其他的方式。如果你不喜欢上面的方法,或者它不适合你的问题,你可以尝试下面的方法。
假设你有is vuex store state:
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>发布于 2018-06-23 00:47:04
您可以简单地检查to url:
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();
}
}如果您有两个具有相同钩子的组件,则可以将beforeEach pathnam和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 }
})https://stackoverflow.com/questions/50991788
复制相似问题