nativescript-vue / nativescript-vue-navigator

A simple router for NativeScript-Vue, built on top of $navigateTo to simplify routing from within components

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

navigation not working inside vuex mutation function

nulele opened this issue · comments

Hello,

I have a vuex store with a mutation function (login) that makes an axios call to the backend.
When login is done I want to navigate to home:

import Vue from 'nativescript-vue'
import Vuex from 'vuex';
Vue.use(Vuex);
import axios from 'axios'

export const auth = {
	namespaced: true,
	state: initialState,
	mutations: {
                ...
	},
	actions: {
		login: function (context, user) {
			axios({
				...
			}).then(result => {
				if(result.data.status === 'success') {
                                        ...
					this.$navigator.navigate('/home', { clearHistory: true });
				}
			}, error => {
				console.error(error);
			});
		},
		logout: function (context) {
                        ...
			this.$navigator.navigate('/login', { clearHistory: true });
		}
	},
	getters: {

	}
};

This is my router:

import Home from './components/Home'
import Login from './components/Login'

export const routes = {
	'/home': {
		component: Home,
		meta: { needsAuth: true }
	},
	'/login': {
		component: Login,
		meta: { needsAuth: false }
	}
}

And this is the main.js

import Vue from 'nativescript-vue'
import Navigator from 'nativescript-vue-navigator'
import { routes } from './routes'
Vue.use(Navigator, { routes })
import authStore from './store/authstore';
import App from './components/App'

new Vue({
	render: h => h(App),
	store: authStore
}).$start()

everything works fine except when it comes to call
this.$navigator.navigate('/home', { clearHistory: true }); or this.$navigator.navigate('/login', { clearHistory: true }); when I get "cannot read property navigate of undefined".
Same error in logout function.

Any idea?

Thanks

A little support please... :(

Replace this.$navigator with Vue.prototype.$navigator. You're not in a Vue context to be able to access it via this

Yes it works!!!! Thank you very much.

Maybe it would be appropriate to document a bit this specific case.