[英]Cannot remove element from array of components (slice, Vue.js)
我正在尝试在 Vue.js 中实现动态添加和删除组件。
slice 方法存在问题,基本上它应该通过传递的索引从数组中删除元素。 要改变数组,我使用slice(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);
}
}
})
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()
此处
您使用的是slice方法,而不是您提供的链接中提到的splice方法。
deleteEvent: function(index) {
this.events.splice(index, 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.