首页 > 解决方案 > 无法从组件数组中删除元素(切片、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);
    }
  }
})

标签: javascriptvue.jsvuejs2

解决方案


 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()which 是响应式的,甚至更好地查看.filter() 这里


推荐阅读