Small program package form form

Small program package form form

In applets, forms are one of the most commonly used components in development. Forms can receive user input and submit it to the server for processing. In order to improve the reusability of the form and reduce code duplication, we can consider encapsulating the form so that the form can be reused in different pages. This article will share how to encapsulate form components in applets.

1. Demand analysis

Before starting to encapsulate the form, we need to clarify the functions and requirements of the form, including which input items are required in the form, the validation rules of the input items, and the operation after the form is submitted.

Here we take the registration form as an example. We need to collect information such as the user's name, mobile phone number, password, and confirmation password. At the same time, we need to perform basic verification on the mobile phone number and password. Finally, after the user clicks the "Register" button, submit it to the server. User information and jump to the login page.

2. Form component packaging

In the applet, we can use <form>tags to create forms, and the functions of the form can be realized by setting different properties. For example, setting bindsubmitproperties can trigger corresponding events when the form is submitted. When encapsulating components, we can encapsulate form-related properties and methods into component properties and methods to facilitate component reuse and maintenance.

1. Component Properties

In order to realize the function of the form, we need to define some properties in the component, including the input items and validation rules in the form. Taking the registration form as an example, we can define the following properties:

properties: {
    
    
  // 输入项
  inputs: {
    
    
    type: Array,
    value: [
      {
    
     name: 'name', label: '姓名', type: 'text', value: '', placeholder: '请输入姓名' },
      {
    
     name: 'mobile', label: '手机号', type: 'number', value: '', placeholder: '请输入手机号' },
      {
    
     name: 'password', label: '密码', type: 'password', value: '', placeholder: '请输入密码' },
      {
    
     name: 'confirmPassword', label: '确认密码', type: 'password', value: '', placeholder: '请确认密码' }
    ]
  },
  // 验证规则
  rules: {
    
    
    type: Object,
    value: {
    
    
      mobile: {
    
    
        required: true,
        tel: true
      },
      password: {
    
    
        required: true,
        minlength: 6,
        maxlength: 20
      },
      confirmPassword: {
    
    
        required: true,
        equalTo: 'password'
      }
    }
  },
  // 按钮文字
  buttonText: {
    
    
    type: String,
    value: '注册'
  }
}

When defining properties, we need to pay attention to the type and default value of the property to ensure the normal operation of the component.

2. Component methods

In order to realize the verification and submission functions of the form, we need to define the corresponding methods in the component. Using the registration form as an example, we can define the following method:

methods: {
    
    
  // 表单验证
  validateForm() {
    
    
    const inputs = this.data.inputs
    const rules = this.data.rules
    for (let i = 0; i// 遍历输入项
    for (let i = 0; i < inputs.length; i++) {
    
    
      const input = inputs[i]
      // 如果输入项有验证规则
      if (rules[input.name]) {
    
    
        // 验证输入项
        const result = this.validateInput(input.value, rules[input.name])
        if (result !== true) {
    
    
          // 如果验证不通过,则提示错误信息并返回false
          wx.showToast({
    
    
            title: result,
            icon: 'none'
          })
          return false
        }
      }
    }
    // 如果所有输入项都验证通过,则返回true
    return true
  },
  // 输入项验证
  validateInput(value, rules) {
    
    
    // 遍历验证规则
    for (let key in rules) {
    
    
      // 如果验证规则为required,表示输入项必填
      if (key === 'required') {
    
    
        if (!value) {
    
    
          return '请输入必填项'
        }
      }
      // 如果验证规则为tel,表示输入项为手机号
      if (key === 'tel') {
    
    
        const reg = /^1[3456789]\d{9}$/
        if (!reg.test(value)) {
    
    
          return '请输入正确的手机号'
        }
      }
      // 如果验证规则为minlength,表示输入项最小长度
      if (key === 'minlength') {
    
    
        if (value.length < rules[key]) {
    
    
          return `请输入至少${
      
      rules[key]}个字符`
        }
      }
      // 如果验证规则为maxlength,表示输入项最大长度
      if (key === 'maxlength') {
    
    
        if (value.length > rules[key]) {
    
    
          return `请输入最多${
      
      rules[key]}个字符`
        }
      }
      // 如果验证规则为equalTo,表示输入项与某一项相等
      if (key === 'equalTo') {
    
    
        const targetValue = this.data.inputs.find(item => item.name === rules[key]).value
        if (value !== targetValue) {
    
    
          return '两次输入的密码不一致'
        }
      }
    }
    // 如果所有验证规则都通过,则返回true
    return true
  },
  // 提交表单
  submitForm() {
    
    
    // 验证表单
    if (!this.validateForm()) {
    
    
      return
    }
    // 表单提交
    const formData = {
    
    }
    this.data.inputs.forEach(item => {
    
    
      formData[item.name] = item.value
    })
    // TODO: 向服务器提交数据
    wx.navigateTo({
    
    
      url: '/pages/login/login'
    })
  }
}

When defining a method, we need to pay attention to the function of the method and the timing of calling it to ensure the normal use of the component.

3. Component template

After defining the component properties and methods, we need to render the form in the template. Using the registration form as an example, we can define the following template:

<form class="form" bindsubmit="submitForm">
  <view class="inputs">
    <template wx:for="{
     
     {inputs}}" wx:key="name">
      <view class="input-item">
        <label class="label">{
   
   {item.label}}</label>
        <input class="input" type="{
     
     {item.type}}" name="{
     
     {item.name}}" value="{
     
     {item.value}}" placeholder="{
     
     {item.placeholder}}" bindinput="onInput" />
      </view>
    </template>
  </view>
  <view class="button-wrapper">
    <button class="button" form-type="submit">{
   
   {buttonText}}</按钮</button>
  </view>
</form>

In the template, we use wx:forinstructions to traverse and render the input items in the form, and use bindinputand form-typeinstructions to bind input events and submit events.

4. Component styles

Finally, we need to define the style of the component to ensure the display effect of the form on the page. Taking the registration form as an example, we can define the following styles:

.form {
    
    
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx;
}

.inputs {
    
    
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.input-item {
    
    
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30rpx;
  width: 100%;
}

.label {
    
    
  font-size: 32rpx;
  color: #333333;
}

.input {
    
    
  flex: 1;
  height: 60rpx;
  padding: 10rpx;
  border: 1rpx solid #CCCCCC;
  border-radius: 5rpx;
  font-size: 28rpx;
  color: #666666;
}

.button-wrapper {
    
    
  margin-top: 60rpx;
  width: 100%;
}

.button {
    
    
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #007AFF;
  color: #FFFFFF;
  border-radius: 5rpx;
  font-size: 36rpx;
  text-align: center;
}

In the style, we have laid out the form and input items, defined the style of the label and input box, and defined the style of the button to ensure that the form has a good display effect on the page.

Summarize

This article mainly introduces how to encapsulate a form component, and gives a simple example. When encapsulating form components, we need to define component properties and methods, component templates and component styles to ensure that the components can be used normally in the page. Through the introduction of this article, I hope to better help you understand the packaging method of form components and apply them in actual projects.

Guess you like

Origin blog.csdn.net/2303_76218115/article/details/130159153