How to navigate using vue router from Vuex actions










36















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 to some other page.



GET_PETS: (state) => 
return $http.get('pets/').then((response)=>
state.commit('SET_PETS', response.data)
)
,
error => this.$router.push(path:"/")
)
}


But this.$router.push(path:"/") gives me following error.




Uncaught (in promise) TypeError: Cannot read property 'push' of undefined




How can this be achieved.



Simulated JsFiddle: here










share|improve this question
























  • it is because you are using it inside an arrow function that treats 'this' as a literal. either convert it to a regular function or use the suggested answers below...

    – EldadT
    Sep 11 '17 at 20:56















36















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 to some other page.



GET_PETS: (state) => 
return $http.get('pets/').then((response)=>
state.commit('SET_PETS', response.data)
)
,
error => this.$router.push(path:"/")
)
}


But this.$router.push(path:"/") gives me following error.




Uncaught (in promise) TypeError: Cannot read property 'push' of undefined




How can this be achieved.



Simulated JsFiddle: here










share|improve this question
























  • it is because you are using it inside an arrow function that treats 'this' as a literal. either convert it to a regular function or use the suggested answers below...

    – EldadT
    Sep 11 '17 at 20:56













36












36








36


3






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 to some other page.



GET_PETS: (state) => 
return $http.get('pets/').then((response)=>
state.commit('SET_PETS', response.data)
)
,
error => this.$router.push(path:"/")
)
}


But this.$router.push(path:"/") gives me following error.




Uncaught (in promise) TypeError: Cannot read property 'push' of undefined




How can this be achieved.



Simulated JsFiddle: here










share|improve this question
















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 to some other page.



GET_PETS: (state) => 
return $http.get('pets/').then((response)=>
state.commit('SET_PETS', response.data)
)
,
error => this.$router.push(path:"/")
)
}


But this.$router.push(path:"/") gives me following error.




Uncaught (in promise) TypeError: Cannot read property 'push' of undefined




How can this be achieved.



Simulated JsFiddle: here







javascript vue.js vuex






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '16 at 16:54







Saurabh

















asked Nov 22 '16 at 8:16









SaurabhSaurabh

30.2k18102169




30.2k18102169












  • it is because you are using it inside an arrow function that treats 'this' as a literal. either convert it to a regular function or use the suggested answers below...

    – EldadT
    Sep 11 '17 at 20:56

















  • it is because you are using it inside an arrow function that treats 'this' as a literal. either convert it to a regular function or use the suggested answers below...

    – EldadT
    Sep 11 '17 at 20:56
















it is because you are using it inside an arrow function that treats 'this' as a literal. either convert it to a regular function or use the suggested answers below...

– EldadT
Sep 11 '17 at 20:56





it is because you are using it inside an arrow function that treats 'this' as a literal. either convert it to a regular function or use the suggested answers below...

– EldadT
Sep 11 '17 at 20:56












5 Answers
5






active

oldest

votes


















67














import router from './router'



and use router.push



Simple like that.






share|improve this answer
































    8














    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.






    share|improve this answer




















    • 1





      This should be the answer specifically for vue 2

      – codely
      May 11 '17 at 16:32


















    7














    This example may help you.



    main.js



    import Vue from "vue";
    import VueRouter from "vue-router";

    ...

    Vue.use(VueRouter);

    export const router = new VueRouter(
    mode: 'hash',
    base: "./",
    routes: [
    path: "/", component: welcome,
    path: "/welcome", component: welcome,

    ]
    )


    actions.js



    import router from "../main.js"

    export const someAction = (commit) =>

    router.push("/welcome");






    share|improve this answer
































      4














      I didn't like keeping my app's location state separate from the rest of my app state in the Store, and having to manage both a Router and a Store, so I created a Vuex module that manages the location state inside the Store.



      Now I can navigate by dispatching actions, just like any other state change:



      dispatch("router/push", path: "/error")


      This has the added benefit of making things like animated page transitions easier to handle.



      It's not hard to roll your own router module, but you can also try mine if you want to:



      https://github.com/geekytime/vuex-router






      share|improve this answer






























        1














        In main.js (the one, where we "install" all modules and create Vue instance, i.e. src/main.js):



        const vm = new Vue(
        el: '#app',
        router,
        store,
        apolloProvider,
        components: App ,
        template: '<App/>'
        )

        export vm


        This is my example, but in our case the most important here is const vm and router



        In your store:



        import vm from '@/main'

        yourMutation (state, someRouteName)
        vm.$router.push(name: someRouteName)



        P.S. Using import vm from '@/main' we can access anything we need in Vuex, for example vm.$root which is needed by some components of bootstrap-vue.



        P.P.S. It seems we can use vm just when everything is loaded. In other words we can not use vm inside someMutation in case, if we call someMutation inside mounted(), because mounted() comes/occurs before vm is created.






        share|improve this answer
























          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40736799%2fhow-to-navigate-using-vue-router-from-vuex-actions%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          67














          import router from './router'



          and use router.push



          Simple like that.






          share|improve this answer





























            67














            import router from './router'



            and use router.push



            Simple like that.






            share|improve this answer



























              67












              67








              67







              import router from './router'



              and use router.push



              Simple like that.






              share|improve this answer















              import router from './router'



              and use router.push



              Simple like that.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jul 2 '18 at 10:52









              Connum

              4,2771929




              4,2771929










              answered Nov 22 '16 at 8:23









              M UM U

              4,17932746




              4,17932746























                  8














                  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.






                  share|improve this answer




















                  • 1





                    This should be the answer specifically for vue 2

                    – codely
                    May 11 '17 at 16:32















                  8














                  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.






                  share|improve this answer




















                  • 1





                    This should be the answer specifically for vue 2

                    – codely
                    May 11 '17 at 16:32













                  8












                  8








                  8







                  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.






                  share|improve this answer















                  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.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited May 23 '17 at 12:18









                  Community

                  11




                  11










                  answered Nov 22 '16 at 15:19









                  GuyCGuyC

                  4,2231425




                  4,2231425







                  • 1





                    This should be the answer specifically for vue 2

                    – codely
                    May 11 '17 at 16:32












                  • 1





                    This should be the answer specifically for vue 2

                    – codely
                    May 11 '17 at 16:32







                  1




                  1





                  This should be the answer specifically for vue 2

                  – codely
                  May 11 '17 at 16:32





                  This should be the answer specifically for vue 2

                  – codely
                  May 11 '17 at 16:32











                  7














                  This example may help you.



                  main.js



                  import Vue from "vue";
                  import VueRouter from "vue-router";

                  ...

                  Vue.use(VueRouter);

                  export const router = new VueRouter(
                  mode: 'hash',
                  base: "./",
                  routes: [
                  path: "/", component: welcome,
                  path: "/welcome", component: welcome,

                  ]
                  )


                  actions.js



                  import router from "../main.js"

                  export const someAction = (commit) =>

                  router.push("/welcome");






                  share|improve this answer





























                    7














                    This example may help you.



                    main.js



                    import Vue from "vue";
                    import VueRouter from "vue-router";

                    ...

                    Vue.use(VueRouter);

                    export const router = new VueRouter(
                    mode: 'hash',
                    base: "./",
                    routes: [
                    path: "/", component: welcome,
                    path: "/welcome", component: welcome,

                    ]
                    )


                    actions.js



                    import router from "../main.js"

                    export const someAction = (commit) =>

                    router.push("/welcome");






                    share|improve this answer



























                      7












                      7








                      7







                      This example may help you.



                      main.js



                      import Vue from "vue";
                      import VueRouter from "vue-router";

                      ...

                      Vue.use(VueRouter);

                      export const router = new VueRouter(
                      mode: 'hash',
                      base: "./",
                      routes: [
                      path: "/", component: welcome,
                      path: "/welcome", component: welcome,

                      ]
                      )


                      actions.js



                      import router from "../main.js"

                      export const someAction = (commit) =>

                      router.push("/welcome");






                      share|improve this answer















                      This example may help you.



                      main.js



                      import Vue from "vue";
                      import VueRouter from "vue-router";

                      ...

                      Vue.use(VueRouter);

                      export const router = new VueRouter(
                      mode: 'hash',
                      base: "./",
                      routes: [
                      path: "/", component: welcome,
                      path: "/welcome", component: welcome,

                      ]
                      )


                      actions.js



                      import router from "../main.js"

                      export const someAction = (commit) =>

                      router.push("/welcome");







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jan 24 '18 at 15:31









                      thomaux

                      13.8k76286




                      13.8k76286










                      answered Dec 14 '16 at 8:59









                      bocaibocai

                      1467




                      1467





















                          4














                          I didn't like keeping my app's location state separate from the rest of my app state in the Store, and having to manage both a Router and a Store, so I created a Vuex module that manages the location state inside the Store.



                          Now I can navigate by dispatching actions, just like any other state change:



                          dispatch("router/push", path: "/error")


                          This has the added benefit of making things like animated page transitions easier to handle.



                          It's not hard to roll your own router module, but you can also try mine if you want to:



                          https://github.com/geekytime/vuex-router






                          share|improve this answer



























                            4














                            I didn't like keeping my app's location state separate from the rest of my app state in the Store, and having to manage both a Router and a Store, so I created a Vuex module that manages the location state inside the Store.



                            Now I can navigate by dispatching actions, just like any other state change:



                            dispatch("router/push", path: "/error")


                            This has the added benefit of making things like animated page transitions easier to handle.



                            It's not hard to roll your own router module, but you can also try mine if you want to:



                            https://github.com/geekytime/vuex-router






                            share|improve this answer

























                              4












                              4








                              4







                              I didn't like keeping my app's location state separate from the rest of my app state in the Store, and having to manage both a Router and a Store, so I created a Vuex module that manages the location state inside the Store.



                              Now I can navigate by dispatching actions, just like any other state change:



                              dispatch("router/push", path: "/error")


                              This has the added benefit of making things like animated page transitions easier to handle.



                              It's not hard to roll your own router module, but you can also try mine if you want to:



                              https://github.com/geekytime/vuex-router






                              share|improve this answer













                              I didn't like keeping my app's location state separate from the rest of my app state in the Store, and having to manage both a Router and a Store, so I created a Vuex module that manages the location state inside the Store.



                              Now I can navigate by dispatching actions, just like any other state change:



                              dispatch("router/push", path: "/error")


                              This has the added benefit of making things like animated page transitions easier to handle.



                              It's not hard to roll your own router module, but you can also try mine if you want to:



                              https://github.com/geekytime/vuex-router







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Mar 30 '18 at 13:52









                              Chris JaynesChris Jaynes

                              2,4162329




                              2,4162329





















                                  1














                                  In main.js (the one, where we "install" all modules and create Vue instance, i.e. src/main.js):



                                  const vm = new Vue(
                                  el: '#app',
                                  router,
                                  store,
                                  apolloProvider,
                                  components: App ,
                                  template: '<App/>'
                                  )

                                  export vm


                                  This is my example, but in our case the most important here is const vm and router



                                  In your store:



                                  import vm from '@/main'

                                  yourMutation (state, someRouteName)
                                  vm.$router.push(name: someRouteName)



                                  P.S. Using import vm from '@/main' we can access anything we need in Vuex, for example vm.$root which is needed by some components of bootstrap-vue.



                                  P.P.S. It seems we can use vm just when everything is loaded. In other words we can not use vm inside someMutation in case, if we call someMutation inside mounted(), because mounted() comes/occurs before vm is created.






                                  share|improve this answer





























                                    1














                                    In main.js (the one, where we "install" all modules and create Vue instance, i.e. src/main.js):



                                    const vm = new Vue(
                                    el: '#app',
                                    router,
                                    store,
                                    apolloProvider,
                                    components: App ,
                                    template: '<App/>'
                                    )

                                    export vm


                                    This is my example, but in our case the most important here is const vm and router



                                    In your store:



                                    import vm from '@/main'

                                    yourMutation (state, someRouteName)
                                    vm.$router.push(name: someRouteName)



                                    P.S. Using import vm from '@/main' we can access anything we need in Vuex, for example vm.$root which is needed by some components of bootstrap-vue.



                                    P.P.S. It seems we can use vm just when everything is loaded. In other words we can not use vm inside someMutation in case, if we call someMutation inside mounted(), because mounted() comes/occurs before vm is created.






                                    share|improve this answer



























                                      1












                                      1








                                      1







                                      In main.js (the one, where we "install" all modules and create Vue instance, i.e. src/main.js):



                                      const vm = new Vue(
                                      el: '#app',
                                      router,
                                      store,
                                      apolloProvider,
                                      components: App ,
                                      template: '<App/>'
                                      )

                                      export vm


                                      This is my example, but in our case the most important here is const vm and router



                                      In your store:



                                      import vm from '@/main'

                                      yourMutation (state, someRouteName)
                                      vm.$router.push(name: someRouteName)



                                      P.S. Using import vm from '@/main' we can access anything we need in Vuex, for example vm.$root which is needed by some components of bootstrap-vue.



                                      P.P.S. It seems we can use vm just when everything is loaded. In other words we can not use vm inside someMutation in case, if we call someMutation inside mounted(), because mounted() comes/occurs before vm is created.






                                      share|improve this answer















                                      In main.js (the one, where we "install" all modules and create Vue instance, i.e. src/main.js):



                                      const vm = new Vue(
                                      el: '#app',
                                      router,
                                      store,
                                      apolloProvider,
                                      components: App ,
                                      template: '<App/>'
                                      )

                                      export vm


                                      This is my example, but in our case the most important here is const vm and router



                                      In your store:



                                      import vm from '@/main'

                                      yourMutation (state, someRouteName)
                                      vm.$router.push(name: someRouteName)



                                      P.S. Using import vm from '@/main' we can access anything we need in Vuex, for example vm.$root which is needed by some components of bootstrap-vue.



                                      P.P.S. It seems we can use vm just when everything is loaded. In other words we can not use vm inside someMutation in case, if we call someMutation inside mounted(), because mounted() comes/occurs before vm is created.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Nov 14 '18 at 23:17

























                                      answered Nov 14 '18 at 22:04









                                      TitanFighterTitanFighter

                                      1,40111334




                                      1,40111334



























                                          draft saved

                                          draft discarded
















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40736799%2fhow-to-navigate-using-vue-router-from-vuex-actions%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          這個網誌中的熱門文章

                                          Barbados

                                          How to read a connectionString WITH PROVIDER in .NET Core?

                                          Node.js Script on GitHub Pages or Amazon S3