首页 > 解决方案 > Vuex 应用程序中“路由器”和“商店”之间的循环依赖关系

问题描述

我有一个带有路由器的 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 } });
    }
  },

从上面的代码中可以看到“路由器”导入“商店”和“商店”导入“路由器”,据我所知,这会导致“商店”在“guardAuth()”中未定义。显然,我可以通过将“handleApiFail”移动到单独的“.js”文件来摆脱这种循环依赖,但我不确定这是一个好主意。是否有更好的解决方案或一些通用方法来解决这种情况?'handleApiFail' 应该是一个突变还是一个简单的函数?突变可以使用“路由器”吗?我真的需要摆脱循环依赖吗(例如,在 C++ 中我不需要)?

标签: vue.js

解决方案


与突变相比,在单独的函数中失败会更好。如果您想在进入路线之前检查它。你可以beforeEnter()在你的路线上使用。

检查此文档beforeEnter其他路由属性


推荐阅读