Vuex应用程序中“路由器”和“商店”之间的循环依赖关系

时间:2018-11-13 13:06:32

标签: vue.js

我有一个带有路由器的vue.js应用程序,它使用以下代码阻止未经授权打开页面:

import Router from 'vue-router';
import store from '../store/index';

function guardAuth(to, from, next) {
  if (store.state.authorizationToken) {
    next();
  } else {
    next({
      name: 'login',
      query: { redirect: to.fullPath },
    });
  }
}

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'toroot',
      redirect: 'login',
    },
    {
      path: '/overview',
      component: Overview,
      beforeEnter: guardAuth,
    },
    ....

和API调用失败时会调用的商店突变:

import axios from 'axios';
import Cookies from 'js-cookie';
import router from '../router/index';

export default new Vuex.Store({
state: {
mutations: {
  handleApiFail(state, err) {
    if (err && !axios.isCancel(err) && state.authorizationToken) {
      // Block subsequent logout calls.
      state.authorizationToken = null;
      // Clear the token cookie just in case.
      Cookies.set('authorizationToken', null);
      // Stop the current and subsequent requests.
      state.cancellationSource.cancel('Authorization token has expired.');
      router.push({ name: 'login', query: { expired: '1', redirect: window.location.pathname } });
    }
  },
从上面的代码中可以看到

,“ router”导入了“ store”,“ store”导入了“ router”,据我所知,这导致在“ guardAuth()”中未定义“ store”。显然,我可以通过将“ handleApiFail”移动到单独的“ .js”文件来摆脱这种循环依赖性,但是我不确定这是一个好主意。是否有更好的解决方案或某些常用方法来停止这种缝合? 'handleApiFail'是突变还是简单函数?突变可以使用“路由器”吗?我真的需要摆脱循环依赖吗(例如,在C ++中我不需要)?

2 个答案:

答案 0 :(得分:0)

最好是handleapi在单独的功能上失败而不是突变。以及是否要在输入路线之前进行检查。您可以在路线上使用beforeEnter()

检查this docs关于beforeEnter或其他路线属性

答案 1 :(得分:0)

商店突变方法完全不应执行任何逻辑。存储仅用于保持您的全局应用程序状态,它们不应执行任何逻辑,例如授权用户或浏览应用程序。您要做的就是将逻辑移出存储区,然后移到进行授权检查的组件中。从那里开始执行$store.commit('unauthorized')$store.commit('authorized', user)之类的操作。应该看起来像这样:

sendAuthRequest.then(
    (success) => {
        $store.commit('authorized', <userVariable>);
        $router.push(...);
    }, (failure) => {
        $store.commit('unauthorized');
        $router.push(...);
    }
);