小程序版vant field输入框批量双向绑定

在进行小程序开发时,我是使用HBulider X uniapp+vue来进行小程序开发的

在使用小程序版vant组件库输入框的时候发现他不能实现数据的双向绑定,这让我们很苦恼,这时我们可以使用一种方式来进行双向绑定
我们可以使用change事件来实现数据监听
在这里插入图片描述

1.声明一个对象,用来存储数据结果
import {
    
    reactive} from "vue";
const user = reactive({
    
    
   	phone: '',
   	code: ''
   })

2.定义输入框

使用:value绑定数据,data-type的值和对象的属性一样,绑定@input事件

<van-field placeholder="请输入手机号"  :value="user.phone" data-type="phone"
				@change='inputUser'></van-field>
<van-field center clearable placeholder="请输入短信验证码" data-type="code" :value="user.code" @change='inputUser' >
</van-field>

3.数据的双向绑定

const inputUser = (e)=>{
    
    
		user[e.target.dataset.type] = e.detail
	}

在这里插入图片描述

完整版

<template>
	<view class="app">
		<van-field placeholder="请输入手机号"  :value="user.phone" data-type="phone"
					 @change='inputUser'></van-field>
		<van-field placeholder="请输入短信验证码" data-type="code" :value="user.code" @change='inputUser' >
				</van-field>
	</view>
</template>

<script setup>
	import {
    
    
		reactive
	} from "vue";
	const user = reactive({
    
    
		phone: '',
		code: ''
	})
	const inputUser = (e)=>{
    
    	
		console.log(e);
		user[e.target.dataset.type] = e.detail
	}
</script>

猜你喜欢

转载自blog.csdn.net/weixin_65565362/article/details/127954668