Vue combines element-ui to realize (button control) dynamic increase and decrease of the input box function.

1. The template part

<template>
  <div>
    <el-button type="primary" @click="add">添加</el-button>
    <el-form ref="form" :model="form" label-width="80px">
      <!-- 这个的v-for是核心是重点,一定要明白! -->
      <div v-for="(item,index) in array" :key="index">  
        <el-form-item>
          <el-input style="width:20%;margin-right:10px" v-model="form.value[index]" placeholder="你好!程序员!"></el-input>
          <el-button type="danger" size="small" icon="el-icon-delete" circle @click="del(index)"></el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

Two, the script part

<script>
export default {
  name:'App',
  data(){
    return {
      array:[1],  //创建一个数组
      form:{
        value:[]  //接收每个input框的值
      }
    }
  },
  methods:{
    // 添加按钮
    add(){
      this.array.push(1)  //通过添加array的值,增加input的个数
    },
    del(index){
      this.form.value.splice(index,1)   //先删除form中value对应索引的值
      this.array.splice(index,1)  //然后删除array对应索引的值,实现点击删除按钮,减少input框效果
    }
  }
}
</script>

<style>

</style>

3. Effect display

This is the initial page

 This is click to add

this is deleted

 

 

4. Detailed description

v-for="(item,index) in array" :key = "index" This is the key point! ! ! !

In layman's terms, it is to use a div (box) to include the input input box, and then use it in the div

v-for="(item,index) in array" :key = "index" ; general idea: the number of this input depends on the length of the array, click the increase button to increase the value of the array array, that is, increase the array An element (length) of the array, if the number of array increases, div will increase by one, because div is in this array, deleting is to delete an element of array, and the length of array will decrease by 1, so the number of div will also increase It will be reduced by one, why use splice to delete, because when the delete button is clicked, the index parameter passed is the index value of the currently clicked div in the array array, so clicking in this way will not cause a bug to delete the wrong data, which basically means that, If you still don’t understand it, go to the official vue document, the list rendering section, if you understand it, you will understand it in general.

Of course, it is not just an input box, but also many structures. I hope this article is useful to you. There is no way, Chinese is taught by a math teacher, and my expressive ability is limited .

Guess you like

Origin blog.csdn.net/weixin_48373171/article/details/130272877