我们如何从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
答案 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
}});