How to navigate using vue router from Vuex actions

前端 未结 5 465
既然无缘
既然无缘 2020-12-03 06:12

I am creating a web app with Vue 2.x and Vuex 2.x. I am fetching some information from a remote location via an http call, I want that if that call fails I should redirect t

5条回答
  •  庸人自扰
    2020-12-03 07:09

    It looks like you aren't injecting your router into your app, hence it being 'undefined'

    In previous versions of vue-router you would: Vue.use(VueRouter), with 2.0 you can inject the router into the app like below:

    const routes = [
      { path: '/foo', component: Foo },
    ]
    
    const router = new VueRouter({
      routes
    })
    
    const app = new Vue({
      router // inject the router
    }).$mount('#app')
    

    this should then make it available as this.$router throughout the app


    Following answering a related question: How to use Vue Router from Vuex state? it seems that Vuex won't receive the router instance at this.$router. Therefore two methods were suggested to provide access to the router instance.

    The first is more direct which involves setting a webpack global to the instance.

    The second involves using Promises with your vuex action that would allow your components to utilise their reference to the router instance following the actions Promise resolving / rejecting.

提交回复
热议问题