【问题标题】:Vue/Vuex > Cannot track state changed when I use Object.defineProperty() methodVue/Vuex > 使用 Object.defineProperty() 方法时无法跟踪状态更改
【发布时间】:2017-11-14 12:28:04
【问题描述】:

我使用Vue.js 和Vuex。

我制作了一个简单的 todolist 应用程序。

我使用Object.defineProperty() 方法使用Vuex 制作了一个完成切换按钮。

当我点击完成切换按钮时,Vue 和 Vuex 无法立即跟踪更改。

当我只是重新分配属性的值时,它只会跟踪变化。

例如

这行得通:

Vuex.Store({
    state: {
        todolist: [
            { todo: 'test1', done: false },
            { todo: 'test2', done: true },
            { todo: 'test3', done: false },
            { todo: 'test4', done: false }
        ]
    },
    mutations: {
        ...
        [Constant.DONE_TOGGLE]: (state, payload) => {
            const changeState = state;
            changeState.todolist[payload.index].done = !state.todolist[payload.index].done;
        },
        ...
    }
});

但这不起作用!

Vuex.Store({
    state: {
        todolist: [
            { todo: 'test1', done: false },
            { todo: 'test2', done: true },
            { todo: 'test3', done: false },
            { todo: 'test4', done: false }
        ]
    },
    mutations: {
        ...
        [Constant.DONE_TOGGLE]: (state, payload) => {
            Object.defineProperty(state.todolist[payload.index], 'done', { value: !state.todolist[payload.index].done });
        },
        ...
    }
});

完成切换的以下代码跟踪更改仅其他更改更改状态。

为什么会这样?

这是我的github repository link。

我的应用位于/EX11/todolistapp。

我的 Vuex 文件在 /EX11/todolistapp/src/store/index.js

感谢您阅读我的问题。 抱歉英语不好。 祝你有美好的一天!

【问题讨论】:

    标签: javascript vue.js vuejs2 vuex defineproperty


    【解决方案1】:

    这是由于 Javascript 的限制——当通过索引完成时,Vue cannot detect changes 对数组元素的限制。

    但是为什么不直接抓取待办事项并直接将其更改为done 属性呢?

    var item = state.todolist[payload.index];
    item.done = !item.done;
    

    【讨论】:

    • 感谢您的回答!这是因为我不想看到 eslint 发出的 'no-param-assign' 警报 :) 我现在知道原因了。祝你编码愉快!
    【解决方案2】:

    我不确定...这是您想要实现的目标吗?

    Vuex.Store({
      state: {
        todolist: [
          { todo: 'test1', done: false },
          { todo: 'test2', done: true },
          { todo: 'test3', done: false },
          { todo: 'test4', done: false }
        ]
      },
      mutations: {
        ...
        [Constant.DONE_TOGGLE]: (state, payload) => {
          var val = !state.todolist[payload.index].done
          state.todolist[payload.index] = Object.assign(state.todolist[payload.index], {done: {value: val}})
        },
        ...
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2021-07-26
      • 2021-06-05
      • 2018-12-21
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      相关资源
      最近更新 更多