javascript - 在命名视图路由器下仅保护一个组件 - 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)
得到了路线,但没有告诉我将呈现哪个组件。我在这里碰壁了。请帮忙。
解决方案
我将向您展示如何支持延迟加载。
//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>
推荐阅读
- ffmpeg - Ffmpeg [NULL @ 0x56390335ae80] 无法找到适合“听”听的输出格式:无效参数
- image - Flutter Image Picker 仅在模拟器中工作
- c++ - 如何让代码检测 C++ 17 中是否存在文件?
- java - Java 和 Android Studio 监听器语法
- c - 如何在 C (LINUX) 中使用 makefile 执行某个部分
- c# - 扩展属性中的 Odata 过滤不起作用
- azure - 如何授予 Azure CLI 图形 API 权限
- python - 用python强制函数args类型
- tableau-api - 设置增量刷新时可以刷新多个表吗?
- fonts - 如何将 otf 字体链接在一起以便它们可以一起使用?