【发布时间】:2022-01-07 12:46:15
【问题描述】:
我在 vue.js 项目中遇到了一个 linting 错误问题。我得到的错误如下所示:
/Users/mikecuddy/Desktop/coding/data_science_projects/statues/client/src/store/modules/common.js
4:1 error Dependency cycle via @/store/index:4 import/no-cycle
我不知道如何摆脱这个错误。我尝试使用 this.$router 和 this.$store 重命名文件,但没有成功。这是我的一些代码:
路由器-> index.js: 数据路径是我想要到达的主要路径。请注意,我已将商店导入文件注释掉 - 这确实消除了依赖错误,但随后我在执行以下操作时遇到了问题:
this.$store.state.common.loginFlag
而不是导入商店并这样做:
store.state.common.loginFlag
import Vue from 'vue';
import VueRouter from 'vue-router';
// import store from '../store/index.js';
// import store from '@/store/index';
import Home from '../views/Home.vue';
Vue.use(VueRouter);
const routes = [
{
path: '/data',
name: 'Data',
component: () => import('../views/Data.vue'),
beforeEnter: (to, from, next) => {
if (this.$store.state.common.loginFlag === false) {
next('/login');
} else {
next();
}
},
beforeRouteLeave: (to, from, next) => {
if (this.$store.state.common.loginFlag === false) {
next('/login');
} else {
next();
}
},
},
];
const router = new VueRouter({
routes,
});
export default router;
存储/模块/common.js:
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
import router from '../../router';
Vue.use(Vuex);
const data = {
userNotFound: false,
passwordNoMatch: false,
loginFlag: false,
};
const getters = {
userNotFound: (state) => state.userNotFound,
passwordNoMatch: (state) => state.passwordNoMatch,
loginFlag: (state) => state.loginFlag,
};
const actions = {
login: ({ commit }, { payload }) => {
const path = 'http://localhost:5000/login';
axios.post(path, payload)
.then((res) => {
if (res.data.login_flag) {
commit('session/setUserObject', res.data.user, { root: true });
commit('setLoginFlag', res.data.login_flag);
// Tried this:
router.push{ name: 'Data' }
// As well as trying this:
this.$router.push({ name: 'Data' });
}
commit('setNoPasswordMatch', res.data.Password_no_match);
commit('setUserNotFound', res.data.Not_found);
})
.catch((error) => {
console.log(error);
});
},
};
// I have mutations but did not think they'd be needed
const mutations = {};
export default {
namespaced: true,
state: data,
getters,
actions,
mutations,
};
在 common.js 文件中我尝试过注释掉:
import router from '../../router';
这似乎有效 - 让依赖循环错误消失,在 router/index.js 文件中我能够到达路由但 this.$store.state.common.loginFlag 出现问题我从“@/store/index”注释掉了导入存储;如果我离开: import store from '@/store/index'; 然后我得到依赖循环错误。
我还在这些其他堆栈页面上找到了一些帮助:
TypeError: Cannot read properties of undefined (reading '$router') vuejs
dependency cycle detected import/no-cycle
我会说我讨厌使用 linter,这就是给我带来问题的原因。
这里是 store/index.js 的代码:
import Vue from 'vue';
import Vuex from 'vuex';
import common from './modules/common';
import session from './modules/session';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
common,
session,
},
});
【问题讨论】:
-
请显示所有相关代码,
@/store/index和router -
我相信我现在已经添加/修改了
-
答案就是这样。通常,一旦您意识到可能存在的问题,就可以接受 circ deps。但是在这里它们是由包含不应该具有的逻辑的商店引起的。
标签: javascript vue.js vuejs2 state router