【问题标题】:Vuex store doesn't update the stateVuex 商店不更新状态
【发布时间】:2019-10-11 08:17:29
【问题描述】:

我的应用程序有一个小功能,如果用户单击特定图像,它应该被列表删除并移动到 Vuex 商店中的另一个。

其实很简单:

// Action
  async movePicture({ commit }, data) {
    try {
      const comment = await this.$axios.$post('/photo-check', data)
      commit('MOVE_PHOTO', photoId)
    } catch (error) {
      throw error.response
    }
  },

  // Mutation
  MOVE_PHOTO: (state, id) => {
    const i = _.findIndex(state.list, p => p.id === id)
    if (i > -1) {
      const photo = state.list[i]
      state.list.splice(i, 1)
      state.visited.push(photo)
    }
  },

关键是不幸的是这张图片不会从list 拼接,我不明白为什么......也许我应该使用特定的东西来更新 Vuex 中的数组,我不知道......我也可以找不到与此不同的解决方案...

【问题讨论】:

  • vuex 没有更新还是你的视图代表数据没有更新?我使用相同的结构并且完美地工作。并且您确定在 state.list 中找到了该项目。
  • movePicture 操作中的photoId 变量从何而来?你检查过splice之前的索引是否正确吗?
  • 您能否确认照片是否已正确添加到state.visited
  • 数据正确传递,id来自照片本身。在我看来,一切都是正确的。如果我添加 2 console.log 以显示 listvisited 我仍然看到项目没有从状态更新。索引总是 > 大于 -1。

标签: javascript vue.js vuex


【解决方案1】:

JavaScript 不擅长处理这些情况。

你应该使用

this.$delete(state.list, index)

Vue.delete 为你做了魔法。

【讨论】:

  • Vue支持拼接,vuejs.org/v2/guide/list.html#Mutation-Methods,你不应该用delete方法
  • @dreijntjens Vue 有,Vuex 没有。
  • Since a Vuex store's state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically. This also means Vuex mutations are subject to the same reactivity caveats when working with plain Vue 由于 vuex 是使用 vue 进行响应式的,因此 vuex 也支持拼接?想知道你在哪里找到它没有吃饱
猜你喜欢
  • 2019-01-25
  • 2017-06-30
  • 2021-04-10
  • 2017-11-09
  • 2021-06-19
  • 2017-07-06
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
相关资源
最近更新 更多