场景:使用vue中的v-for循环动态的添加input,在编辑的时候需要获取input的id进而获取编辑值传入后台。由于通过:id传入的id有可能空值,因此我采用了拼接的方式将属性值和下标index拼接在一起做为id,成功解决空值问题。

html代码:

<el-form-item label="姓名:">
	<div>
		<el-input v-model="dialogTable.name" placeholder="姓名" style="width:200px;"></el-input>
		<el-button @click="add">新增</el-button>
	</div>
	<div v-model="this.dialogTable.lists">
		<div v-for="(item, index) in this.dialogTable.lists" :key="index" >
			<el-input :id="nameId(item,index)" :value="item.name" style="width:200px;" @change="editNmae(item,index)"></el-input>
			<el-button @click="delete(index)">删除</el-button>
		</div>
	</div>
</el-form-item>

 js代码:

var editName = function(item,index) {
	/*var name = $('#'+item.name).val();*///此处不用这种方式获取id值,是因为id可能为特殊字符,比如逗号分号
	var id = nameId(item,index);
	var name = document.getElementById(id).value;
	this.dialogTable.lists[index].name = name;
}

var nameId = function(item,index) {
	if(item.name == null){
		return index+"name";
	}else{
		return item.name+index;
	}
}
var add = function() {	
		this.dialogTable.lists.push(
				{name:this.dialogTable.name});}
	this.dialogTable.name = undefined;
}

回头看的时候恍然大悟,大费周折实现的效果,使用vue的v-model绑定便可以实现

<el-form-item label="姓名:">
	<div>
		<el-input v-model="dialogTable.name" placeholder="姓名" style="width:200px;"></el-input>
		<el-button @click="add">新增</el-button>
	</div>
	<div v-model="this.dialogTable.lists">
		<div v-for="(item, index) in this.dialogTable.lists" :key="index" >
			<el-input v-model="item.name" style="width:200px;"></el-input>
			<el-button @click="delete(index)">删除</el-button>
		</div>
	</div>
</el-form-item>

 

Logo

前往低代码交流专区

更多推荐