【发布时间】:2019-03-01 18:26:14
【问题描述】:
使用vue.js 和vue-router 我想拥有应用程序的全局状态属性(组件之间共享的东西)并根据该属性的值阻止路由。
例如,如果状态未初始化,我想将所有路由重定向到根“/”。 我尝试了以下方法:
Vue.use(Router)
const router = new Router({
routes: routes
})
// global status property
Vue.prototype.$isInitialized = false
router.beforeEach((to, from, next) => {
if (!this.$isInitialized) { // <--- does not work, can't access Vue instance from here
next("/")
}
else {
next()
}
})
此代码不起作用,因为我无法从全局路由器挂钩访问 Vue 实例。在 Vue 中实现这种行为的正确方法是什么?
【问题讨论】:
-
如果我没记错的话,
this.a.app或this.app中附加了 Vue 实例,this是路由器实例,而不是 Vue 本身。router.beforeEach是全局导航守卫,一般情况下,最好使用this来引用单个组件,使用this来引用全局Vue 实例会导致将来混淆。 -
您好,感谢您的回答,从我可以看到 router.app 或 router.apps[0] 指的是全局实例 Vue,而不是我的应用程序的特定实例,因此对全局的任何更改属性 $isInitialized 从那里将不可见
-
既然你是直接添加到
Vue.prototype,你不能说if (! Vue.prototype.$isInitialized) { ...吗?不确定这是否可行或与最佳实践相差多远。
标签: javascript vue.js vue-router