Reputation: 504
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
Upvotes: 2
Views: 3873
Reputation: 4349
$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
}});
Upvotes: 3