I'am trying to implements dynamic adding and removing components in Vue.js.
There is a problem with slice method, basically it should remove element from array by passed index. To mutate an array i use slice(i,1) .
According to this answer, modifying array in this way should help me, but is's not working.
What i am doing wrong?
Here is my code and a codepen:
<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);
}
}
})