在使用Vue#2.1.6创建页面内容编辑器时,我遇到了一个问题。我使用Vue动态组件来处理每一篇文章。当我在v-for列表中插入一篇新文章时,所有剩下的文章都会被重置到它们的初始状态。下面是示例https://jsfiddle.net/3jowy381/
Vue.component('type-a', {
template: '<div class="style-a" @click="ready">{{context.name}} prepared: {{prepared}}</div>',
props: ['context'],
data: function () {
return {
prepared: false
}
},
methods: {
ready: function () {
this.prepared = true;
}
}
});
Vue.component('type-b', {
template: '<div class="style-b" @click="ready">{{context.name}} prepared: {{prepared}}</div>',
props: ['context'],
data: function () {
return {
prepared: false
}
},
methods: {
ready: function () {
this.prepared = true;
}
}
});
Vue.component('type-c', {
template: '<div class="style-c" @click="ready">{{context.name}} prepared: {{prepared}}</div>',
props: ['context'],
data: function () {
return {
prepared: false
}
},
methods: {
ready: function () {
this.prepared = true;
}
}
});
new Vue({
el: '#main',
data: {
position: 0,
modules: [
{context: {name: 'article-init-a'}, type: 'type-a'},
{context: {name: 'article-init-b'}, type: 'type-b'},
{context: {name: 'article-init-c'}, type: 'type-c'}
]
},
methods: {
insertA: function () {
this.modules.splice(this.position, 0, {context: {name: 'new-article-a'}, type: 'type-a'})
},
insertB: function () {
this.modules.splice(this.position, 0, {context: {name: 'new-article-b'}, type: 'type-b'})
},
insertC: function () {
this.modules.splice(this.position, 0, {context: {name: 'new-article-c'}, type: 'type-c'})
}
}
})您可以单击文章设置已准备好的文章,然后再插入新的文章。下面的所有文章都会自动变得毫无准备。Vue似乎是在重新创造它们。有办法四处走走吗?
发布于 2016-12-15 07:43:44
每当您在modules中添加新的modules时,它将重新呈现modules数组中的所有项目,并再次初始化所有这些组件,将ready变量重置为false。
通过在其中一个元素中放置一个已挂载生命周期挂钩,这是显而易见的。
一种解决方案是将prepared属性移动到上下文本身,因为它看起来像项目的属性,因此它可以放在项目名称旁边。假设这是我修改了你的小提琴,请检查。
new Vue({
el: '#main',
data: {
position: 0,
modules: [
{context: {name: 'article-init-a', prepared: false}, type: 'type-a'},
{context: {name: 'article-init-b', prepared: false}, type: 'type-b'},
{context: {name: 'article-init-c', prepared: false}, type: 'type-c'}
]
},
methods: {
insertA: function () {
this.modules.splice(this.position, 0, {context: {name: 'new-article-a', prepared: false}, type: 'type-a', prepared: false})
},
....
....https://stackoverflow.com/questions/41158573
复制相似问题