需求:在form表单中点击可以添加dom元素,如下图
思路:使用数字循环,点击之后数字加1,实现元素的添加。data中定义其变量的时候,将其定义为数组
<div v-for="index of internetNum" :key="`${index}A`">
<el-row>
<el-col :span="8">
<el-form-item :label="`网卡${index}`">
<el-input v-model="form.cards.name[index-1]" placeholder="请输入"/>
</el-form-item>
</el-col>
<el-col v-if="index === 1" :span="8">
<svg-icon icon-class="addMore" @click="num = num +1"/>
</el-col>
</el-row>
<el-row>
<el-col :span="8">
<el-form-item :label="`MAC${index}`">
<el-input v-model="form.cards.mac[index-1]" placeholder="请输入"/>
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item :label="`IP${index}`">
<el-input v-model="form.cards.ip[index-1]" placeholder="请输入"/>
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item :label="`掩码${index}`">
<el-input v-model="form.cards.mask[index-1]" placeholder="请输入"/>
</el-form-item>
</el-col>
</el-row>
</div>
data(){
return{
internetNum:1,
form:{
cards:{
name:[],
mac:[],
ip:[],
mask:[]
}
}
}
}
index of 3 数字循环
:label="`IP${index}`"
form.cards.ip[index-1]
最后在清空form表单的时候遇到一个问题:使用 this.$refs[formName].resetFields()无法清空cards中的数据,尝试添加上props 但是无效,最后使用最傻的办法,手动置空,如下:
this.form.cards = {
name: [],
mac: [],
ip: [],
mask: []
}
后期优化:
首先将数据结构优化入下:
this.form.cards = [{
name:'',
mac:'',
ip:'',
mask:''
}]
代码:
<div v-for="(item,index) of form.cards" :key="`${index}A`">
<el-row>
<el-col :span="8">
<el-form-item :label="`网卡${index+1}`">
<el-input v-model="form.cards[index].name" placeholder="请输入"/>
</el-form-item>
</el-col>
<el-col v-if="index === 0" :span="8">
<svg-icon icon-class="addMore" @click="addItem"/>
</el-col>
<el-col v-if="index !== 0" :span="8">
<svg-icon icon-class="reduceOne" @click="reduceItem(index)"/>
</el-col>
</el-row>
<el-row>
<el-col :span="8">
<el-form-item :label="`MAC${index}`">
<el-input v-model="form.cards[index].mac" placeholder="请输入"/>
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item :label="`IP${index}`">
<el-input v-model="form.cards[index].ip" placeholder="请输入"/>
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item :label="`掩码${index}`">
<el-input v-model="form.cards[index].mask" placeholder="请输入"/>
</el-form-item>
</el-col>
</el-row>
</div>
methods:{
addItem(){ // 增加一个元素
this.form.cards.push({
name:'',
mac:'',
ip:'',
mask:''
})
},
reduceItem(index){ //减少一个元素
this.form.cards.splice(index,1)
}
}