Vue.js的计算状态和突变状态存在问题

时间:2018-09-01 23:22:04

标签: javascript vue.js vuex

我看到Vuex状态管理中设置的绑定组件存在问题。

我有一个状态存储,如下:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    id: 0,
    contentBlocks: []
  },
  mutations: {
    addContentBlock(state, contentBlock) {
      contentBlock.id = state.id
      state.contentBlocks.push(contentBlock)
      state.id += 1
    },
    updateContentBlock(state, contentBlock) {
      const index = state.contentBlocks.findIndex(block => block.id === contentBlock.id)
      Vue.set(state.contentBlocks, index, contentBlock)
    },
    removeContentBlock(state, contentBlock) {
      const index = state.contentBlocks.findIndex(block => block.id === contentBlock.id)
      Vue.delete(state.contentBlocks, index)
    }
  }
})

然后我在state.contentBlocks中的baseComponent.vue上进行如下循环:

<v-container pa-0 v-for="(contentBlock, index) in contentBlocks" v-bind:key="contentBlock.index">
  <component v-bind:is="contentBlock.blockComponent" v-bind:contentBlock="contentBlock"></component>
</v-container>

然后,我通过添加,更新和删除内容块来对state.contentBlocks进行突变。 (我从基本组件添加了块,从绑定到<component></component>的子组件中删除和更新。

我在get中将state.contentBlocks变异为BaseComponent.vueBaseComponent.vue

computed: {
    contentBlocks: () => store.state.contentBlocks,
}

更新时,我会在控制台中看到以下内容:

enter image description here

一切都很好。然后,我删除索引1处的块,该块在状态级别“起作用”:

enter image description here

但是DOM没有发挥作用:

enter image description here

(!!)在上面,索引0和2根据需要是正确的,但是索引2中的内容是已删除索引1的内容(!!?)帮助! :D

1 个答案:

答案 0 :(得分:1)

baseComponent.vue中,使用计算属性遍历内容块,而不是vuex存储的状态:

<v-container pa-0 v-for="(contentBlock, index) in blocks" v-bind:key="contentBlock.index">
  <component v-bind:is="contentBlock.blockComponent" v-bind:contentBlock="contentBlock"></component>
</v-container>

computed: {
  blocks () {
    return this.$store.getters['contentBlocks']
  }
}

您还需要将相应的吸气剂添加到商店中:

export default new Vuex.Store({
  state: {
    id: 0,
    contentBlocks: []
  },
  getters: {
    contentBlocks: (state) => state.contentBlocks 
  }
  mutations: {
    addContentBlock(state, contentBlock) {
      contentBlock.id = state.id
      state.contentBlocks.push(contentBlock)
      state.id += 1
    },
    updateContentBlock(state, contentBlock) {
      const index = state.contentBlocks.findIndex(block => block.id === contentBlock.id)
      Vue.set(state.contentBlocks, index, contentBlock)
    },
    removeContentBlock(state, contentBlock) {
      const index = state.contentBlocks.findIndex(block => block.id === contentBlock.id)
      Vue.delete(state.contentBlocks, index)
    }
  }
})

不相关,但是您可以简单地将removeContentBlock突变为:

state.contentBlocks = state.contentBlocks.filter({id} => id !== contentBlock.id)

更新

component元素上添加键:

<v-container pa-0 v-for="(contentBlock, index) in blocks" v-bind:key="contentBlock.index">
  <component v-bind:is="contentBlock.blockComponent" v-bind:contentBlock="contentBlock" :key="contentBlock.id"></component>
</v-container>