在一个项目中,有个功能需要动态添加input,灵光一闪,我就进行了以下操作:
代码实现
<template>
<!--旅客-->
<div
class="panel is-shadow people-info-box traveler-item"
v-for="(item, index) in travelerList"
:key="index"
>
<div class="panel-header">
<i class="iconfont icon-wode"></i>
旅客{{index+1}}
</div>
<div class="panel-body">
<el-form-item label="中文姓" >
<el-input v-model="item.ch_surname" type="text" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="中文名" >
<el-input v-model="item.ch_name" type="text" autocomplete="off"></el-input>
</el-form-item>
</div>
</div>
<!--旅客-->
</template>
<script>
export default {
data () {
return {
travelerList: [],
travelerItem: {
ch_surname: null,
ch_name: null,
surname: null,
name: null,
sex: null,
birthday: null,
country_id: null,
passport_number: null,
passport_end_time: null,
weight: null,
shoe_size: null,
height: null,
cellphone: null
},
}
}
methods: {
handleChangeTravelerNum (newVal, oldVal) {
if (newVal > oldVal) {
// 加1
this.travelerList.push(this.travelerItem)
} else {
this.travelerList.splice(this.travelerList.length -1, 1)
}
},
}
}
</script>
代码思路:
避免麻烦,在data下新建一个有初始值的travelerItem,在数量增加的时候,就将这个对象push到travelerList里,如果数量减的时候就从travelerList后面开始移除,这完成了旅客数量增减操作。v-for中的item是travelerList子项,那我input元素就用 v-model 来绑定值,值用item.xxx就搞定啦
以下是实现效果:
Animation.gif完美,增减旅客数量没什么问题,整个功能完成!!
开什么玩笑,如果就这样我还写这篇东西???
再往下看:
Animation.gif我x,坑爹啊!!!在旅客1里输入数据的时候,旅客2中竟然同时出现了相同的内容!!!这还得了
思索了一会,进行了这样改动(看data和methods中的注释)
<template>
<!--旅客-->
<div
class="panel is-shadow people-info-box traveler-item"
v-for="(item, index) in travelerList"
:key="index"
>
<div class="panel-header">
<i class="iconfont icon-wode"></i>
旅客{{index+1}}
</div>
<div class="panel-body">
<el-form-item label="中文姓" >
<el-input v-model="item.ch_surname" type="text" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="中文名" >
<el-input v-model="item.ch_name" type="text" autocomplete="off"></el-input>
</el-form-item>
</div>
</div>
<!--旅客-->
</template>
<script>
export default {
data () {
return {
travelerList: []
//这里的travelerItem没了
}
}
methods: {
handleChangeTravelerNum (newVal, oldVal) {
// travelerItem 到这里啦
const travelerItem = {
ch_surname: null,
ch_name: null,
surname: null,
name: null,
sex: null,
birthday: null,
country_id: null,
passport_number: null,
passport_end_time: null,
weight: null,
shoe_size: null,
height: null,
cellphone: null
}
if (newVal > oldVal) {
// 加1
this.travelerList.push(travelerItem)
} else {
this.travelerList.splice(this.travelerList.length -1, 1)
}
},
}
}
</script>
网友评论