一、template部分
<template>
<div>
<el-button type="primary" @click="add">添加</el-button>
<el-form ref="form" :model="form" label-width="80px">
<!-- 這個的v-for是核心是重點,一定要明白! -->
<div v-for="(item,index) in array" :key="index">
<el-form-item>
<el-input style="width:20%;margin-right:10px" v-model="form.value[index]" placeholder="你好!程序員!"></el-input>
<el-button type="danger" size="small" icon="el-icon-delete" circle @click="del(index)"></el-button>
</el-form-item>
</div>
</el-form>
</div>
</template>
二、script部分
<script>
export default {
name:'App',
data(){
return {
array:[1], //創(chuàng)建一個數組
form:{
value:[] //接收每個input框的值
}
}
},
methods:{
// 添加按鈕
add(){
this.array.push(1) //通過添加array的值,增加input的個數
},
del(index){
this.form.value.splice(index,1) //先刪除form中value對應索引的值
this.array.splice(index,1) //然后刪除array對應索引的值,實現點擊刪除按鈕,減少input框效果
}
}
}
</script>
<style>
</style>
三、效果展示
這是初始頁面
?這是點擊添加
這是刪除的
?
?
四、詳細說明
v-for="(item,index)in array" :key = "index"這個是重點?。?!!
通俗點將,就是用一個div(盒子)將input輸入框包括起來,然后在div中使用
v-for="(item,index)in array" :key = "index";大致思路:這個input的個數取決于array這個數組的長度,點擊增加按鈕,增加array數組的數值,也就是增加array數組的一個元素(長度),array增加了個數,div就會增加一個,因為div在這個數組中,刪除就是刪除array的一個元素,array的長度就會減小1,所以div的個數也會跟著減少一個,為什么使用splice進行刪除,因為點擊刪除按鈕,傳遞的index參數是當前點擊的div在array數組中的索引值,所以這樣點擊不會出現刪錯數據的bug,基本就是這個意思,還不明白的話就去看vue官方文檔,列表渲染這節(jié),看懂了,大體上就懂了。文章來源:http://www.zghlxwxcb.cn/news/detail-518398.html
當然了,不只是input框,還可以是很多結構,希望本文對你有用,沒辦法,語文是數學老師教的,表達能力有限,不懂的可以私信我,看到必回!文章來源地址http://www.zghlxwxcb.cn/news/detail-518398.html
到了這里,關于vue結合element-ui實現(按鈕控制)動態(tài)增加減少input框功能。的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!