从 actions.ts 访问 vue-router

Accessing vue-router from actions.ts

我们如何从 actions.ts 文件中访问 Vue 路由器实例? this.$routerthis.$route 在以下上下文中不可用:

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

$路由器:

要在商店操作中访问 $router,您可以这样做:

将您的路由器声明移动到名为 router.ts

的单独文件中
const router = new VueRouter({
  routes,
  linkActiveClass: "active"
});
export default router;

将您的 router 导入 actions.ts 并使用它代替 this.$router,如下所示:

import router from './router';

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

$route.fullPath

关于$route.fullPath,您可以在调度动作时将其作为负载的属性传递

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

然后在 LOGOUT 操作中像这样使用它

router.push({path:"login", query: {
  sessionTimedout: true,
  redirect: params.redirectPath
}});