Eslint state already declared [Vuex]

╄→гoц情女王★ 提交于 2020-12-29 09:10:34

问题


I am running ESLint and I am currently running into the following ESLint error:

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
};

What would be the best way to fix this?


回答1:


The best way to fix would be to read the docs about the eslint "no-shadow" rule.

From this documentation, the best solution would probably be to include an exception for this one variable with the "allow" option.

You can add this with a comment to the js file to keep the exeption local:

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



回答2:


The best solution is @Linus Borg's answer.

If you are looking for an alternative, you can declare the state constant below the rest. This will prevent variable shadowing because state will not be declared in the outer-scope yet.

Example:

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
};



回答3:


If it's not too late

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
};

basically you define your store data as data, and you export it as state state: data




回答4:


Had the same issue as I was using an airbnb eslint config which is incompatible with vuex.

This worked for me, after restarting dev environment.

I created a new .eslintrc.js file in my store folder and added them there

"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"
    ]
  }
],


来源:https://stackoverflow.com/questions/43843180/eslint-state-already-declared-vuex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!