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
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.
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') .
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.
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) { // }, }, });
import router from './router'
and use router.push
Simple like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With