javascript - Vue 实例状态和路由重定向
问题描述
使用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 中实现这种行为的正确方法是什么?
解决方案
现在解决了将全局属性附加到路由器实例而不是 Vue 实例:
Vue.use(Router)
// global status property
Router.prototype.$isAppInitialized = false
const router = new Router({
routes: routes
})
router.beforeEach((to, from, next) => {
if (to.path !== "/" && !router.$isAppInitialized) {
next("/")
}
else {
next()
}
})
这是可行的,因为可以访问组件中的路由器实例并更新全局属性,但对我来说感觉就像一个黑客。请让我知道是否有更好的方法来做到这一点。
推荐阅读
- c++ - 在visual studion 2017中安装opencv
- c - 通过 pthread_join() 加入两个 pthread 不能按预期工作
- android - Android Studio 或 IntellIj 导出设置不包含插件列表?
- r - 循环遍历变量,绘制它们并创建 pdf
- android - 片段附加和分离后 RecyclerView 项目未更改
- c# - 在获取线程的循环中执行任务被中止
- angular5 - 如何从 Angular 5 中的 url 下载 pdf 文件
- architecture - 洋葱结构与六边形相比
- php - PHP html实体上标2以正方形打印K
- java - Android AppUsageStatistics 示例