zoukankan      html  css  js  c++  java
  • 微信小程序实战:表单与选择控件的结合

    先上代码。

    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数组中可以加对象,里面的每一个对象都会去验证。

    以上。

  • 相关阅读:
    Kubernetes如何支持有状态服务的部署?
    Web 安全入门-书籍及建议
    docker kubernetes swarm spring cloud结合学习资源
    docker-compose 完整打包发布, 多服务,多节点SPRING CLOUD ,EUREKA 集群
    Kubernetes权威指南学习笔记(一)
    解决k8s出现pod服务一直处于ContainerCreating状态的问题的过程
    Spark操作—aggregate、aggregateByKey详解
    maven设置------settings.xml文件学习
    Scala详细环境安装与配置
    内存泄露
  • 原文地址:https://www.cnblogs.com/foxcharon/p/12261013.html
Copyright © 2011-2022 走看看