微信小程序实战:表单与选择控件的结合

先上代码。

login.wxml

<mp-toptips msg="{{error}}" type="error" show="{{error}}"></mp-toptips>

<view class="page-body">
  <mp-form id="form" rules="{{rules}}" models="{{formData}}">
    <mp-cells title="信息绑定" >
      <mp-cell prop="name" title="姓名" ext-class="cell" >
          <input bindinput="formInputChange" data-field="name" class="weui-input"/>
      </mp-cell>
      <mp-cell prop="phone" title="手机号" ext-class="cell" >
          <input bindinput="formInputChange" data-field="phone" class="weui-input"/>
      </mp-cell>
      <mp-cell prop="company" title="单位名称" ext-class="cell" >
        <picker bindchange="bindPickerChange1" value="{{company}}" range="{{companyArray}}" range-key="name">
          <view class="picker">
            {{formData['company'] ? companyArray[company].name : '请选择'}}
            <input hidden data-field="company" value="{{formData['company'] ? companyArray[company].name : '请选择'}}" class="weui-input"/> 
          </view>
        </picker>
      </mp-cell> 

      
    </mp-cells>
  </mp-form>

  <view class="weui-btn-area">
      <button class="weui-btn" type="primary" bindtap="submitForm">确定</button>
  </view>
</view>

login.wxss

.cell .weui-cell__hd{
  width:200rpx;
}

login.js

// pages/login/login.js

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 单位
    company:0,
    companyArray:[
      {
        id:0,
        name:'a'
      },
      {
        id:1,
        name: 'b'
      }
    ],
    rules: [{
      name: 'name',
      rules: { required: true, message: '姓名必填' },
    }, {
      name: 'phone',
      rules: [{ required: true, message: '手机号必填' }, { mobile: true, message: '手机号格式不对' }],
    }, {
      name: 'company',
      rules: { required: true, message: '单位名称必填' },
    }],
    formData:{}
  },
formInputChange(e) { const { field } = e.currentTarget.dataset this.setData({ [`formData.${field}`]: e.detail.value }) }, bindPickerChange1: function (e) { this.setData({ company: e.detail.value, [`formData.company`]: e.detail.value }) }, submitForm() { // console.log(this.selectComponent('#form')) this.selectComponent('#form').validate((valid, errors) => { // console.log('valid', valid, errors) if (!valid) { const firstError = Object.keys(errors) if (firstError.length) { this.setData({ error: errors[firstError[0]].message }) } } else { // wx.showToast({ // title: '校验通过' // }) // console.log(this.data.formData) wx.showToast({ title: '绑定成功' }) try { // 同步接口立即写入 wx.setStorageSync('user', JSON.stringify(this.data.formData)) let token = wx.getStorageSync('user') // console.log(token) if (typeof app.globalData.haveToken === "boolean") { app.globalData.haveToken = true app.globalData.reloadFlag = true } // console.log(app.globalData.haveToken) wx.switchTab({ url: '../index/index' }) } catch (e) { console.log('写入value2发生错误') } } }) } })
picker 是小程序自带的组件,类似于select,选择控件。
mp-* 是WeUI 的组件,使用之前需要在json文件中引入。
login.json
{
  "component": true,
  "usingComponents": {
    "mp-toptips": "../../weui-miniprogram/toptips/toptips",  // 悬浮提示
    "mp-cell": "../../weui-miniprogram/cell/cell",  // 布局用的
    "mp-cells": "../../weui-miniprogram/cells/cells",  // 布局用的,依赖 cell
    "mp-form": "../../weui-miniprogram/form/form"  // 表单,表单验证需要
  }
}

下面是细节分析。

<mp-cell prop="company" title="单位名称" ext-class="cell" >
        <picker bindchange="bindPickerChange1" value="{{company}}" range="{{companyArray}}" range-key="name">
          <view class="picker">
            {{formData['company'] ? companyArray[company].name : '请选择'}}
            <input hidden data-field="company" value="{{formData['company'] ? companyArray[company].name : '请选择'}}" class="weui-input"/> 
          </view>
        </picker>
      </mp-cell> 

formData是存表单数据的,默认空对象。

一开始的时候肯定是没有值的,所以选之前都会提示 请选择。

只要选过了,就有值了,表单验证就能通过,否则不能通过。

隐藏的输入框是配合表单的,可能不需要。

bindPickerChange1: function (e) {
    this.setData({
      company: e.detail.value,
      [`formData.company`]: e.detail.value
    })
  },

对应的change 方法。

set 了两个值,一个是显示用的,一个是表单用的。

submitForm() {
    // console.log(this.selectComponent('#form'))
    this.selectComponent('#form').validate((valid, errors) => {
      // console.log('valid', valid, errors)
      if (!valid) {
        const firstError = Object.keys(errors)
        if (firstError.length) {
          this.setData({
            error: errors[firstError[0]].message
          })

        }
      } else {
        // wx.showToast({
        //   title: '校验通过'
        // })
        // console.log(this.data.formData)
        wx.showToast({
          title: '绑定成功'
        })
        try {
          // 同步接口立即写入
          wx.setStorageSync('user', JSON.stringify(this.data.formData))
          let token = wx.getStorageSync('user')
          // console.log(token)
          if (typeof app.globalData.haveToken === "boolean") {
            app.globalData.haveToken = true
            app.globalData.reloadFlag = true
          }
          // console.log(app.globalData.haveToken)
          wx.switchTab({
            url: '../index/index'
          })
        } catch (e) {
          console.log('写入value2发生错误')
        }
      }   
    })
  }

表单验证方法。

校验规则是 this.data.rules.

this.data.rules 会和 this.data.formData 进行比对,如果rule里面相应值 formData没有就会校验失败,这是最简单的非空校验。

更复杂的校验在rules[index].rules数组中可以加对象,里面的每一个对象都会去验证。

以上。

原文地址:https://www.cnblogs.com/foxcharon/p/12261013.html