我正在试验Vue.JS,并将组件动态组合在一起。
有一个奇怪的问题,尽管它似乎正在正确地更新数据,但是如果我通过调用splice()删除其中一个框,它总是删除呈现的HTML中的最后一个项。
这里有一个小提琴的例子。我在用Chrome做测试。
https://jsfiddle.net/afz6jjn0/
只是为了子孙后代,下面是Vue组件代码:
Vue.component('content-longtext', {
template: '#content-longtext',
props: {
model: { type: String, required: true },
update: { type: Function, required: true }
},
data() {
return {
inputData: this.model
}
},
methods: {
updateContent(event) {
this.update(event.target.value)
}
},
})
Vue.component('content-image', {
template: '#content-image',
})
Vue.component('content-list', {
template: '#content-list-template',
props: {
remove: { type: Function, required: true },
update: { type: Function, required: true },
views: { type: Array, required: true }
},
methods: {
removeContent(index) {
this.remove(index)
},
updateContent(index) {
return (content) => this.update(index, content)
},
},
})
Vue.component('content-editor', {
template: '#content-editor',
data() {
return {
views: [
{type: 'content-longtext', model: 'test1'},
{type: 'content-longtext', model: 'test2'},
{type: 'content-longtext', model: 'test3'},
{type: 'content-longtext', model: 'test4'},
{type: 'content-longtext', model: 'test5'},
],
}
},
methods: {
newContentBlock(type) {
this.views.push({type: 'content-longtext', model: ''})
},
updateContentBlock(index, model) {
this.views[index].model = model
},
removeContentBlock(index) {
this.views.splice(index, 1)
},
},
})
let app = new Vue({
el: '#app'
})发布于 2017-09-12 09:26:50
多亏了这文档,我成功地解决了这个问题。
关键是,如果您还没有一个唯一的键,您需要将对象的数组索引存储在对象本身中,这是因为当您变异源数组时,您也在变异它的键,并且就Vue而言,当它呈现时,最后一项是丢失的,而不是删除的项。
views: [
{index: 0, type: 'content-longtext', model: 'test1'},
{index: 1, type: 'content-longtext', model: 'test2'},
{index: 2, type: 'content-longtext', model: 'test3'},
{index: 3, type: 'content-longtext', model: 'test4'},
{index: 4, type: 'content-longtext', model: 'test5'},
],
...
newContentBlock(type) {
this.views.push({index: this.views.length, type: 'content-longtext', model: ''})
},一旦存储了数组索引,就需要将:key绑定添加到模板中的迭代器中,并绑定存储的值。
<div v-for="(currentView, index) in views" :key="currentView.index">
<component :is="currentView.type" :model="currentView.model" :update="updateContent(index)"></component>
<a v-on:click="removeContent(index)">Remove</a>
</div>最后,在更改数组时,必须确保保持索引的完整性。
removeContentBlock(index) {
this.views
.splice(index, 1)
.map((view, index) => view.index = index)
},https://stackoverflow.com/questions/46170992
复制相似问题