近些天,我在寫表單數據提交及回顯問題,中間遇到了很多坑,經過看文檔,各種百度,從而一一解決。
表單中包括的東西特別多,從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],
})
}
這樣就能保證每次都會有值賦給他。
在做項目的時候,牽扯到各種效果問題,因此有各種各樣的問題擺在我的面前,一一解決之後,就想分享一下,還是不錯的。如果表單中有問題,可以具體諮詢我。