2

How do we get access to the Vue router instance from within our actions.ts file? this.$router and this.$route aren't available in the following context:

boot.ts:

import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';
import store from './services/store'
import * as log from 'loglevel'

Vue.use(VueRouter);

log.setLevel("trace");

const router = new VueRouter({
    routes,
    linkActiveClass: "active"
});

new Vue({
    el: '#app-root',
    router: router,
    store: store,
    render: h => h(require('./layouts/app.vue.html'))
});

actions.ts:

import { http, httpClass } from './http';
import { DomainAppModel } from '../models/domainApps';
import Vue from 'vue';

var actions = {
    LOGOUT: function ({ commit }, params) {
        return new Promise((resolve, reject) => {
            http.logout().then(result => {
                commit('CLEAR_STATE');                
                // this.$router and this.$route not available
                this.$router.push({
                    path:"login", 
                    query: {
                        sessionTimedout: true,
                        redirect: this.$route.fullPath
                    }
                });
            });
        });      
    }
}

export default actions
1
  • Resolve the Promise in the .then handler via resolve() and then wherever you're dispatching the action: this.$store.dispatch('LOGOUT', params).then(() => this.$router.push({...}) Commented Oct 27, 2017 at 16:11

1 Answer 1

3

$router:

In order to access $router in the store actions you can do it like this:

move your router declaration to a separate file named router.ts

const router = new VueRouter({
  routes,
  linkActiveClass: "active"
});
export default router;

Import your router in actions.ts and use it instead of this.$router like this:

import router from './router';

// then use the router like this
router.push({path: 'login'})

$route.fullPath

Concerning $route.fullPath, you can pass it as a property of the payload when the action is dispatched

this.$store.dispatch('LOGOUT', {redirectPath: this.$route.fullPath})

then use it like this in the LOGOUT action

router.push({path:"login", query: {
  sessionTimedout: true,
  redirect: params.redirectPath
}});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.