I'm currently working on implementing dynamic addition and removal of components in Vue.js.
I've encountered an issue with the slice method, which is supposed to remove an element from an array by the provided index. To modify the array, I am using slice(i,1).
According to an answer found here, this method should work for me, but unfortunately, it's not functioning as expected.
What am I doing incorrectly?
Below is the code snippet along with a link to a corresponding 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);
}
}
})