近些天,我在写表单数据提交及回显问题,中间遇到了很多坑,经过看文档,各种百度,从而一一解决。
表单中包括的东西特别多,从API可以看得出来,小程序API中的表单有:input/button/picker/label等,我主要用到了input/button/picker,其中在picker问题的解决上费了很多时间。我个人认为,小程序的API文档写的挺详细的,当然,这也是我后来才发现的,最初的时候遇到问题就百度,后来有人提醒我看文档就能找到。因此我现在几乎遇到问题首先会查文档,查不出来的再去百度。因此建议大家遇到问题夺取查文档。
首先是表单的写法吧。以下是官方提供的几个属性,是特别有用的。在使用中,具体是如何使用的呢?
<form bindsubmit="formSubmit">
<view class="formLine">
<view class="addAddress addAddressLine">
<text class="addAddressleft">收货人</text>
<input type="text" name="receiveName" placeholder-class="phcolor" focus placeholder="姓名" minlength="2"/>
</view>
<view class="addAddress addAddressLine">
<text class="addAddressleft">选择城市</text>
<picker mode="region" bindchange="bindRegionChange" value="{{region}}" custom-item="{{customItem}}">
<text style='{{ region[0]?"display: none":"display: block"}}' class='choosecity'>请选择城市</text>
<text class="picker" name="provinceName">{{region[0]}}</text>
<text class="picker" name="cityName"> {{region[1]}}</text>
<text class="picker" name="districtName"> {{region[2]}}</text>
</picker>
<text class="iconfont icon-pull-right-line icon-member-management-style"></text>
</view>
<view class="addAddress addAddressLine">
<text class="addAddressleft">收货地址</text>
<input type="text" name="receiveAddress" placeholder-class="phcolor" placeholder="收货地址"/>
</view>
</view>
<!--添加收货地址,保存按钮-->
<view class="saveAddress btn-area">
<button type="primary" size="{{primarySize}}" formType="submit">保存收货地址 </button>
</view>
</form>
在这段代码中,包含了input框,picker城市选择三级联动,button提交按钮。全部被form包起来,另外,form中有该属性
bindsubmit="formSubmit"文档中已经说明,在接收的时候是如何实现的。
//保存收货地址
formSubmit: function (e) {
let that = this
const { receiveName, receiveAddress } = e.detail.value
}
就是在js中这样接收的。接收到之后,就可以做数据校验,等操作。关键的地方就是提交之后的数据,如何接收,
在这里将button的formType定义为submit也是至关重要的
<button type="primary" size="{{primarySize}}" formType="submit">保存收货地址 </button>
文档上已经说明,当点击 <form/>
表单中 formType 为 submit 的 <button/>
组件时,会将表单组件中的 value 值进行提交,需要在表单组件中加上 name 来作为 key。
在使用picker进行三级联动效果的展示的时候,如果region:['','','',]这样定义的时候,在页面中是没法进行选择的,只用当他不为空的时候,才会出现选择列表,这样的情况,可以在wxml页面中进行一个判断,
<text style='{{ region[0]?"display: none":"display: block"}}' class='choosecity'>请选择城市</text>
也就是如果是空的,就显示这样的文字。具体picker是如何触发,如何传值,看api就好了。另外,在数据回显的时候,如果这个picker列表不进行修改,那么会将空值传回去,原因是若不修改该变量,事件是没有触发的,这个时候需要做一个非空判断,传具体的参数,
if (that.data.region[0] == "" || that.data.region[1] == "" || that.data.region[2] == ""){
that.setData({
province: that.data.address.provinceName,
city: that.data.address.cityName,
district: that.data.address.districtName,
})
}else{
that.setData({
province: that.data.region[0],
city: that.data.region[1],
district: that.data.region[2],
})
}
这样就能保证每次都会有值赋给他。
在做项目的时候,牵扯到各种效果问题,因此有各种各样的问题摆在我的面前,一一解决之后,就想分享一下,还是不错的。如果表单中有问题,可以具体咨询我。