Skip to content
Advertisement

Cannot remove element from array of components (slice, Vue.js)

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);
    }
  }
})

Advertisement

Answer

 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>

I read this before its to do with Vue and reactive states. .slice() is non-reactive so it returns a copy of the data without altering the original( i.e. non-reactive). Use the .splice() which is reactive or even better look at the .filter() here

Advertisement