Vue js beforeRouteEnter
Vue js beforeRouteEnter
我正在为我的应用程序使用 laravel 和 vuejs,每个用户都有一个角色。现在我想限制用户按角色访问 vue 路由,如果他们无法访问该页面,则将他们重定向到另一条路由。我正在为 vuejs 使用 beforeRouteEnter,但出现错误
data() {
return{
role: '',
}
},
mounted() {
axios.post('/getRole')
.then((response) => this.role = response.data)
.catch((error) => this.errors = error.response.data.errors)
},
beforeRouteEnter (to, from, next) {
if (this.role === 'Admin') {
next()
}else {
next('/')
}
}
我收到这个错误
app.js:72652 TypeError: Cannot read property 'role' of undefined
at beforeRouteEnter (app.js:90653)
at routeEnterGuard (app.js:72850)
at iterator (app.js:72690)
at step (app.js:72464)
at runQueue (app.js:72472)
at app.js:72726
at step (app.js:72461)
at app.js:72465
at app.js:72711
at app.js:72539
- 你不能在
beforeRouteEnter
函数中使用this
,因为在路由更新之前,你的组件的vm不存在。
- 考虑到你把角色信息放在你的虚拟机中,你可以使用
next
来获取你的虚拟机:
beforeRouteEnter(to, from, next) {
next(vm => {
// put your logic here
if (vm.role === 'Admin') {
}
})
}
- 实际上,你应该使用 Global Router Guard ,并将你的角色信息放在全局区域,这样你就可以在你的目标组件创建之前重定向你的路由
我正在为我的应用程序使用 laravel 和 vuejs,每个用户都有一个角色。现在我想限制用户按角色访问 vue 路由,如果他们无法访问该页面,则将他们重定向到另一条路由。我正在为 vuejs 使用 beforeRouteEnter,但出现错误
data() {
return{
role: '',
}
},
mounted() {
axios.post('/getRole')
.then((response) => this.role = response.data)
.catch((error) => this.errors = error.response.data.errors)
},
beforeRouteEnter (to, from, next) {
if (this.role === 'Admin') {
next()
}else {
next('/')
}
}
我收到这个错误
app.js:72652 TypeError: Cannot read property 'role' of undefined
at beforeRouteEnter (app.js:90653)
at routeEnterGuard (app.js:72850)
at iterator (app.js:72690)
at step (app.js:72464)
at runQueue (app.js:72472)
at app.js:72726
at step (app.js:72461)
at app.js:72465
at app.js:72711
at app.js:72539
- 你不能在
beforeRouteEnter
函数中使用this
,因为在路由更新之前,你的组件的vm不存在。 - 考虑到你把角色信息放在你的虚拟机中,你可以使用
next
来获取你的虚拟机:
beforeRouteEnter(to, from, next) {
next(vm => {
// put your logic here
if (vm.role === 'Admin') {
}
})
}
- 实际上,你应该使用 Global Router Guard ,并将你的角色信息放在全局区域,这样你就可以在你的目标组件创建之前重定向你的路由