我试图在Vue.js中实现动态添加和删除组件。
切片方法存在一个问题,它基本上应该通过传递索引从数组中删除元素。要变异数组,我使用片(i,1)。
根据这的回答,以这种方式修改数组应该会对我有帮助,但并不有效。
我做错什么了?
这是我的代码和一个码页
<div id="app">
<button @click="addNewComp">add new component</button>
<template v-for="(comp,index) in arr">
<component
:is="comp"
:index="index"
@remove-comp="removeComp(index)"
></component>
</template>
</div>
<script type="text/x-template " id="compTemplate">
<h1> I am a component {{index}}
<button v-on:click="$emit('remove-comp')">X</button>
</h1>
</script> const newComp = Vue.component("newComp",{
template:"#compTemplate",
props:['index']
})
new Vue({
el:"#app",
data:{
arr:[newComp]
},
methods:{
addNewComp:function(){
this.arr.push(newComp);
console.log(this.arr);
},
removeComp:function(i){
console.log(i);
this.arr.slice(i,1);
console.log(this.arr);
}
}
})发布于 2018-05-02 14:14:21
const newComp = Vue.component("newComp",{
template:"#compTemplate",
props:['index']
})
new Vue({
el:"#app",
data:{
arr:[newComp]
},
methods:{
addNewComp:function(){
this.arr.push(newComp);
},
removeComp:function(i, a){
console.log('i', i, a, typeof i);
this.arr.splice(i,1);
}
}
})<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17-beta.0/vue.js"></script>
<div id="app">
<button @click="addNewComp">add new component</button>
<template v-for="(comp,index) in arr">
<component
:is="comp"
:index="index"
@remove-comp="removeComp(index, 100+index)"
:key="`${index}`"
></component>
</template>
</div>
<script type="text/x-template " id="compTemplate">
<h1> I am a component {{index}}
<button v-on:click="$emit('remove-comp')">X</button>
</h1>
</script>
我读过这篇文章之前,它是关于Vue和反应性状态的。.slice()是非反应性的,因此它返回数据的副本而不改变原始数据(即非反应性)。使用.splice(),它是反应性的,甚至更好地查看.filter() 这里
发布于 2018-05-02 14:11:42
您使用的是片方法,而不是您提供的链接中提到的剪接方法。
deleteEvent: function(index) {
this.events.splice(index, 1);
}https://stackoverflow.com/questions/50136513
复制相似问题