在vue中表单项可以通过v-model的方式达到数据的双向绑定的效果,但是在微信小程序中没有这种方式,我们只能通过h5的方式来收集表单项的数据
第一种方式(id)
login.wxml中:
定义唯一的值id
bindinput方法可以监听到当前输入框的值
<text class="tit">手机号码</text>
<input bindinput="handleInput" id="phone" type="text" placeholder="请输入手机号码"/>
<text class="tit">密码</text>
<input bindinput="handleInput" id="password" type="password" placeholder="请输入密码"/>
login.js中
data: {
phone:'', //用户账号
password:'', //用户密码
},
// 表单项事件的回调
handleInput(event){
let type=event.currentTarget.id //根据表单定义的id情况,id只有两种情况phone或者password 适合传唯一值
// 更新数据
this.setData({
[type]:event.detail.value // event.detail.value可以获取到输入的值,根据点击的表单更新表单里面对应的数据,type应该是变量,所以应该用[]
})
},
第二种方式(data-key=value)
这里使用data-type=""来定义 data-key可以定义多个,而id只可以定义唯一的一个
login.wxml:
<view class="input-item">
<text class="tit">手机号码</text>
<input bindinput="handleInput" type="text" data-type="phone" placeholder="请输入手机号码"/>
</view>
<view class="input-item">
<text class="tit">密码</text>
<input bindinput="handleInput" type="password" data-type="password" placeholder="请输入密码"/>
</view>
login.js中,其实和id的使用方式是差不多的,只不过获取data-key的方式有些差别
data: {
phone:'', //用户账号
password:'', //用户密码
},
// 表单项事件的回调
handleInput(event){
let type=event.currentTarget.dataset.type data-key=value //适合传多个值 // 更新数据
this.setData({
[type]:event.detail.value //根据点击的表单更新表单里面对应的数据,type应该是变量,所以应该用[]
})
},