从actions.ts访问vue-router

时间:2017-10-27 15:52:47

标签: vue.js vue-router

我们如何从actions.ts文件中访问Vue路由器实例?这个。$ router和this。$ 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

1 个答案:

答案 0 :(得分:1)

<强> $路由器:

要在商店操作中访问$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
}});