使用Vue循环input输入框的取值问题

  • 使用Vue循环生成input输入框时如何动态绑定v-model ?

相信大家使用Vue动态循环生成input输入框时可能遇到过如下问题:
Vue通过v-for可便捷的生成DOM结构,但循环input时会有一个v-model的属性,要通过v-model取值,便要为它动态绑定一个字段,而此时我们又不好在Vue的data属性中提前定义好input中v-model所需的字段,到这一步相信很多同学都放弃使用v-for循环生成input了,还是老老实实的使用js拼接字符串吧。emoji…

经过我不断的探索之后,终于找到了一个解决办法:
可以在js代码中先提前定义一个数组(inputData),数组长度即为要生成的input数量,数组中再push一个空对象object进去,注意:一定要push一个对象{}进去,因为只有对象中才能动态的去添加自定义的字段key。然后再把该数组inputData赋值给Vue实例data中的inputList,inputList即为v-for循环所需的数组。

代码如下:

<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title></title>
		<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js" type="text/javascript" charset="utf-8">
		</script>
	</head>
	<body>
		<div id="app">
			<div>
				<input type="" v-for="(item,index) in inputList" :key="index" v-model="item.value" name="" id=""
					value="" />
			</div>
			<button type="button" @click="getData">取值</button>
		</div>
		<script type="text/javascript">
			var inputData = []
			for (var i = 0; i < 5; i++) {
				inputData.push({});
			};
			new Vue({
				el: "#app",
				data: {
					inputList: inputData
				},
				methods: {
					getData() {
						var json = this.inputList;
						console.log(JSON.parse(JSON.stringify(json)))
					},
				}
			})
		</script>
	</body>
</html>

demo截图:

在这里插入图片描述
即可获取到控制台中对应的数组,此数组即为input各个value值的集合。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐