Vue实现输入框动态添加删除,并添加必填校验
    		       		warning:
    		            这篇文章距离上次修改已过430天,其中的内容可能已经有所变动。
    		        
        		                
                
<template>
  <div>
    <div v-for="(item, index) in inputList" :key="index">
      <input v-model="item.value" @input="validateInput(index, item.value)">
      <button @click="removeInput(index)">删除</button>
    </div>
    <button @click="addInput">添加输入框</button>
    <p v-if="errorMessage">{{ errorMessage }}</p>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      inputList: [{ value: '' }],
      errorMessage: null,
    };
  },
  methods: {
    addInput() {
      this.inputList.push({ value: '' });
    },
    removeInput(index) {
      this.inputList.splice(index, 1);
    },
    validateInput(index, value) {
      if (value.trim() === '') {
        this.errorMessage = `第 ${index + 1} 个输入框不能为空`;
      } else {
        this.errorMessage = null;
      }
    }
  }
};
</script>这段代码实现了一个输入框的动态管理功能,包括添加、删除输入框,以及对输入框内容的必填验证。每个输入框都绑定了一个 validateInput 方法来进行实时验证,如果输入值为空格,则显示错误信息。
评论已关闭