nativescript-vue / nativescript-vue-navigator

A simple router for NativeScript-Vue, built on top of $navigateTo to simplify routing from within components
MIT License
98 stars 10 forks source link

navigation not working inside vuex mutation function #8

Closed nulele closed 5 years ago

nulele commented 5 years ago

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

nulele commented 5 years ago

A little support please... :(

rigor789 commented 5 years ago

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

nulele commented 5 years ago

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

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