【问题标题】:How to reference to element from state in foreach (Vuex)?如何从foreach(Vuex)中的状态引用元素?
【发布时间】:2021-11-01 13:48:07
【问题描述】:

我在我的 vue 应用程序中使用 vuex。在 store 中是一个声明的对象:

    state: {
        list: {
            a: false,
            b: false,
            c: false
        }
    }

In mutation 是在参数中接收数组的突变,例如:el: ['a', 'b']el 数组中的那些元素必须在状态中的list 对象中设置为 true。我为此使用了一个 foreach 循环:

    mutations: {
        SET_LIST(state, el) {
            el.forEach(element => {
                if (state.list.element) {
                    state.list.element = true;
                }
            });
        }
    }

但我收到一个错误:error 'element' is defined but never used。 因为element没有使用,不知道怎么正确引用。

我在互联网上搜索并找到了这个解决方案:state.list[element]。然后我没有收到错误,但它不起作用。

【问题讨论】:

    标签: vue.js foreach vuex store


    【解决方案1】:

    使用the bracket notation[]动态获取属性:

       mutations: {
            SET_LIST(state, el) {
                el.forEach(element => {
                    if (Object.keys(state.list).includes(element)) {
                        state.list[element] = true;
                    }
                });
            }
        }
    

    【讨论】:

    • 它不起作用,在这个解决方案中,当我调用 commit ('SET_LIST', ["a"]) 时,if (state.list[element]) 永远不会被调用
    • if (state.list.hasOwnProperty(element))替换if (state.list.element)
    • 我收到错误:Do not access Object.prototype method 'hasOwnProperty' from target object
    • 试用if(Object.keys(state.list).includes(element))
    猜你喜欢
    • 2023-03-20
    • 1970-01-01
    • 2021-07-21
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    相关资源
    最近更新 更多