vue实现点击添加按钮添加一行input框,点击删除则删除input框,至少保留一行无法删除
    		       		warning:
    		            这篇文章距离上次修改已过429天,其中的内容可能已经有所变动。
    		        
        		                
                以下是一个简单的Vue组件示例,实现了点击按钮添加输入框,点击删除按钮删除输入框,至少保留一行的功能。
<template>
  <div>
    <div v-for="(item, index) in inputList" :key="index">
      <input type="text" />
      <button @click="removeInput(index)" :disabled="inputList.length === 1">删除</button>
    </div>
    <button @click="addInput">添加</button>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      inputList: [{}], // 初始有一个输入框
    };
  },
  methods: {
    addInput() {
      this.inputList.push({});
    },
    removeInput(index) {
      this.inputList.splice(index, 1);
    },
  },
};
</script>在这个例子中,inputList 数组用于跟踪输入框的数量。addInput 方法用于添加新的输入框,它将一个空对象添加到 inputList 数组中。removeInput 方法用于删除输入框,它会从数组中移除指定索引的元素。v-for 指令用于渲染 inputList 数组中的每个元素,并且每个元素都有一个对应的删除按钮。通过使用 :disabled 绑定,我们确保至少有一个输入框的删除按钮是不可点击的。
评论已关闭