Vuex 改变state数据后丢失响应式

发布时间 2023-09-18 21:23:44作者: Karle

背景

  • 在网络请求后,将数据保存到Vuex中,需要对state中数据进行修改,使用到mutation
  • 需求是在state.votes中找到对应的对象,然后替换成新的对象
const mutations = {
  UPDATEVOTE(state, data) {
    const { votes } = state
    const originVoteIndex = votes.findIndex((v) => {
      return v.id === data.id
    })
    state.votes[originVoteIndex] = data
  },
}

问题

  • 当完成网络请求,在组件中使用computed去获取state.votes,发现依然是旧的数据
  • 而通过Vue devtool 发现Vuex中的votes是更新后的数据
computed: {
    votes() {
        retrun this.$store.state.votes
    }
}

 

原因与解决

  • 因为上文操作中使得state.votes丢失了响应式:state.votes[originVoteIndex] = data导致计算属性无法实时获取到新的数据
  • 数组操作需要使用以下方法来保留响应式:
    arr.push()
    arr.pop()
    arr.shift()
    arr.unshift()
    arr.sort()
    arr.reverse()
    arr.splice()
  • 因此对于state.votes的更新方法需要用到上诉方法而不能通过index进行替换
  • //可行方法
    const mutations = {
      UPDATEVOTE(state, data) {
        const { votes } = state
        const originVoteIndex = votes.findIndex((v) => {
          return v.id === data.id
        })
        state.votes.splice(originVoteIndex, 1, data)
      },
    }