单击按钮后删除创建的输入

delete created inputs after clicking a button

我有一个可以添加输入的代码,使用 @click="addInput()" .

现在我正在尝试使用 @click="deleteInput() 删除这些输入。我尝试用 this.inputs.splice(index, 1) 来做到这一点 - 但是当我尝试这样做时,只会删除我最后的输入..但我不知道为什么..

如何解决我要删除的特定输入将被删除?

我在 addInput -> name 输入中的附加代码来自子元素

谢谢你帮我!

我的模板:

<template>
  <div >
    <div class="mt-2" v-for="(id, index) in inputs" :key="index">
      <div class="row mb-3">
        <b-button-group class="col-md-12">
          <b-button class="col-md-8" v-b-toggle="toggleElementInChildVue" variant="danger"></b-button>
          <b-button @click="deleteInput(index)" class="col-md-4" variant="danger">Delete this!</b-button>
        </b-button-group>
      </div>
    </div>

    <div>
      <b-button @click="addInput()">Add Input</b-button>
    </div>
  </div>
</template>

我的脚本:

<script>
export default {
  name: 'test',

  data() {
    return {
      inputs: [{
        name: "",
      }],
    }
  },

  methods: {
    deleteInput(index) {
      this.inputs.splice(index, 1)
    },
  
    addInput() {
      this.inputs.push({
        name: "",
      })
    },
  },  
}
</script>

看起来您的删除方法有效,请检查代码段:

new Vue({
  el: '#demo',
  data() {
    return {
      inputs: [{
        name: "aa",
      }],
    }
  },

  methods: {
    deleteInput(index) {
      this.inputs.splice(index, 1)
    },
  
    addInput() {
      this.inputs.push({
        name: "bb",
      })
    },
  },  
})

Vue.config.productionTip = false
Vue.config.devtools = false
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />

<!-- Load polyfills to support older browsers -->
<script src="//polyfill.io/v3/polyfill.min.js?features=es2015%2CIntersectionObserver" crossorigin="anonymous"></script>

<!-- Load Vue followed by BootstrapVue -->
<script src="//unpkg.com/vue@latest/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<!-- Load the following for BootstrapVueIcons support -->
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>

<div id="demo">
  <div >
    <div class="mt-2" v-for="(name, index) in inputs" :key="index">
      <div class="row mb-3">
        <b-button-group class="col-md-12">
          <b-button class="col-md-8"  variant="danger">{{name}}</b-button>
          <b-button @click="deleteInput(index)" class="col-md-4" variant="danger">Delete this!</b-button>
        </b-button-group>
      </div>
    </div>

    <div>
      <b-button @click="addInput()">Add Input</b-button>
    </div>
  </div>
      
</div>