我看到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.vue
到BaseComponent.vue
:
computed: {
contentBlocks: () => store.state.contentBlocks,
}
更新时,我会在控制台中看到以下内容:
一切都很好。然后,我删除索引1处的块,该块在状态级别“起作用”:
但是DOM没有发挥作用:
(!!)在上面,索引0和2根据需要是正确的,但是索引2中的内容是已删除索引1的内容(!!?)帮助! :D
答案 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>