首页 > 解决方案 > Vue 实例状态和路由重定向

问题描述

使用vue.jsvue-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 中实现这种行为的正确方法是什么?

标签: javascriptvue.jsvue-router

解决方案


现在解决了将全局属性附加到路由器实例而不是 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()
    }
}) 

这是可行的,因为可以访问组件中的路由器实例并更新全局属性,但对我来说感觉就像一个黑客。请让我知道是否有更好的方法来做到这一点。


推荐阅读