Eslint 状态已经声明 [Vuex]

Eslint state already declared [Vuex]

我是 运行 ESLint,我目前 运行 遇到以下 ESLint 错误:

error 'state' is already declared in the upper scope no-shadow

const state = {
    date: '',
    show: false
};

const getters = {
    date: state => state.date,
    show: state => state.show
};

const mutations = {
    updateDate(state, payload) {
        state.date = payload.date;
    },
    showDatePicker(state) {
        state.show = true;
    }
};

export default {
    state,
    getters,
    mutations
};

解决此问题的最佳方法是什么?

最好的修复方法是阅读有关 eslint "no-shadow" 规则的文档。

根据本文档,最好的解决方案可能是使用 "allow" 选项为这个变量包含一个例外。

您可以在 js 文件中添加注释以保持本地异常:

/* eslint no-shadow: ["error", { "allow": ["state"] }]*/

最好的解决方案是

如果您正在寻找替代方案,可以在其余部分下方声明 state 常量。这将阻止 variable shadowing 因为 state 不会在外部范围内声明。

示例:

const getters = {
    date: state => state.date,
    show: state => state.show
};

const mutations = {
    updateDate(state, payload) {
        state.date = payload.date;
    },
    showDatePicker(state) {
        state.show = true;
    }
};

const state = {
    date: '',
    show: false
};

export default {
    state,
    getters,
    mutations
};

如果还不算太晚的话

const data = {
    date: '',
    show: false
};

const getters = {
    date: state => state.date,
    show: state => state.show
};

const mutations = {
    updateDate(state, payload) {
        state.date = payload.date;
    },
    showDatePicker(state) {
        state.show = true;
    }
};

export default {
    state: data,
    getters,
    mutations
};

基本上,您将商店数据定义为 data,然后将其导出为状态 state: data

遇到了与我使用与 vuex 不兼容的 airbnb eslint 配置相同的问题。

重新启动开发环境后,这对我有用。

我在我的存储文件夹中创建了一个新的 .eslintrc.js 文件并将它们添加到那里

"no-shadow": ["error", { "allow": ["state"] }],
"no-param-reassign": [
  "error",
  {
    "props": true,
    "ignorePropertyModificationsFor": [ // All properties except state are in the ignorePropertyModificationsFor array by default.
      "state",
      "acc",
      "e",
      "ctx",
      "req",
      "request",
      "res",
      "response",
      "$scope"
    ]
  }
],

根据@allochi 的回答,这是我必须做的才能使它与 Vue 3 一起工作,它使用 Vuex 4,它更喜欢为状态返回一个函数:

// store.js

const data = {
  // ...
};

const getters = {
  // ...
};

const mutations = {
  // ...
};

const actions = {
  // ...
};

export default {
  state() { return data; },
  getters,
  mutations,
  actions
};

如果你需要从外部导入特定的功能,你将不得不这样做:

import mystore from './mystore';

const Store = createStore({
  state: mystore.state,
  getters: mystore.getters,
  mutations: mystore.mutations,
  actions: mystore.actions
});

如果你真的不会用,我只会推荐这个 /* eslint no-shadow: ["error", { "allow": ["state"] }]*/