效果图如下:

<template>
<div class="dynamic-input-demo">
<el-form ref="form" label-width="80px">
<!-- 动态输入框列表 -->
<div v-for="(input, index) in inputs" :key="index" class="input-item">
<el-form-item :label="'输入框 ' + (index + 1)">
<el-input
v-model="input.value"
placeholder="请输入内容"
style="width: 200px; margin-right: 10px"
></el-input>
<el-button
type="danger"
icon="el-icon-delete"
circle
@click="removeInput(index)"
v-if="inputs.length > 1"
></el-button>
</el-form-item>
</div>
<!-- 添加按钮 -->
<el-form-item>
<el-button type="primary" @click="addInput">添加输入框</el-button>
</el-form-item>
</el-form>
<!-- 显示数据 -->
<div class="data-view">
<pre>{{ inputs }}</pre>
</div>
</div>
</template>
<script>
export default {
data() {
return {
inputs: [{ value: "" }] // 初始包含一个空输入框
};
},
methods: {
// 添加输入框
addInput() {
this.inputs.push({ value: "" });
},
// 删除输入框
removeInput(index) {
this.inputs.splice(index, 1);
}
}
};
</script>
<style>
.dynamic-input-demo {
padding: 20px;
}
.input-item {
margin-bottom: 10px;
}
.data-view {
margin-top: 20px;
padding: 15px;
background: #f5f7fa;
border-radius: 4px;
}
pre {
margin: 0;
font-family: monospace;
}
</style>
核心功能说明:
-
数据管理:
- 使用
inputs数组来存储所有输入框的值 - 每个输入框对应数组中的一个对象(便于扩展更多属性)
- 使用
-
动态添加:
- 点击"添加输入框"按钮会向数组添加新对象
- 新增的输入框会自动渲染
-
删除功能:
- 每个输入框右侧有删除按钮(当只剩一个时隐藏)
- 删除时会根据索引移除对应数组元素
-
实时数据展示:
- 底部展示了当前 inputs 数组的内容
- 方便观察数据变化
扩展建议:
- 添加验证功能:
// 在 el-form 上添加 rules 验证规则
rules: {
inputs: [
{ required: true, message: '不能为空', trigger: 'blur' }
]
}
2. 限制最大数量
addInput() {
if (this.inputs.length >= 5) {
this.$message.warning('最多添加5个输入框');
return;
}
this.inputs.push({ value: "" });
}
3. 添加清空所有按钮:
<el-button @click="inputs = [{ value: '' }]">清空所有</el-button>
4. 保存数据功能:
saveData() {
console.log('保存的数据:', this.inputs);
// 这里可以添加提交到服务器的逻辑
}
这个实现方式利用了 Vue 的响应式特性,通过操作数组来实现动态增减界面元素。Element UI 的组件样式和交互行为可以保持界面美观和用户体验一致性。

1068

被折叠的 条评论
为什么被折叠?



