【问题标题】:Vue instance status and route redirectVue 实例状态和路由重定向
【发布时间】:2019-03-01 18:26:14
【问题描述】:

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

【问题讨论】:

  • 如果我没记错的话,this.a.appthis.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


【解决方案1】:

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

这是可行的,因为可以访问组件中的路由器实例并更新全局属性,但对我来说感觉就像是 hack。如果有更好的方法,请告诉我。

【讨论】:

  • 通常我更喜欢设置一个全局的 Vuex,它可以做同样的事情,但是 Vuex 给你更多的权力,功能(比如 getter 来计算复杂的变化)只是我的看法。
猜你喜欢
  • 2018-04-09
  • 1970-01-01
  • 2017-07-21
  • 2020-12-18
  • 2018-04-13
  • 2021-12-28
  • 1970-01-01
  • 2017-07-25
  • 2016-11-23
相关资源
最近更新 更多