Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to navigate using vue router from Vuex actions

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

like image 830
Saurabh Avatar asked Nov 22 '16 08:11

Saurabh


People also ask

How do I access my Vue router state?

To access Vuex state when defining Vue Router routes, we can import the store in the file with the Vue Router hooks. import Vuex from "vuex"; const store = new Vuex. Store({ state: { globalError: "", }, mutations: { setGlobalError(state, error) { state.

How do I redirect my Vue router?

But what if you want to redirect programmatically, without using an anchor tag at all? If you're using Vue Router you'll push the new URL onto the router in order to do a redirect: this. $router. push('www.yoursite.com/blog') .

How do I use Vue routing?

To start with routing, we need to add the vue-router. js file. Take the code from https://unpkg.com/vue-router/dist/vue-router.js and save it in the file vue-router.

How do you call actions on Vuex?

You can call another Vuex action by passing the name of that action as a string as the first argument of dispatch : const store = new Vuex. Store({ actions: { walk(context) { context. dispatch("goForward"); }, goForward(context) { // }, }, });


Video Answer


1 Answers

import router from './router'

and use router.push

Simple like that.

like image 192
Marek Urbanowicz Avatar answered Oct 13 '22 20:10

Marek Urbanowicz