阿里云主机折上折
  • 微信号
Current Site:Index > Form components (input, checkbox, picker, etc.)

Form components (input, checkbox, picker, etc.)

Author:Chuan Chen 阅读数:13151人阅读 分类: uni-app

uni-app provides a rich set of form components for building user interaction interfaces. These components include input, checkbox, picker, etc., which can meet data collection requirements in various scenarios. Below is a detailed introduction to the usage methods and common scenarios of these components.

input Component

The input component is one of the most basic form components, used to receive text input from users. In uni-app, the input component supports multiple types, including text, number, password, etc.

<template>
  <view>
    <input type="text" v-model="username" placeholder="Please enter username" />
    <input type="password" v-model="password" placeholder="Please enter password" />
    <input type="number" v-model="age" placeholder="Please enter age" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: '',
      age: ''
    }
  }
}
</script>

Common properties of the input component:

  • type: Input type, such as text, number, password, etc.
  • v-model: Two-way data binding
  • placeholder: Hint text in the input box
  • maxlength: Maximum input length
  • disabled: Whether it is disabled

checkbox Component

The checkbox component is used for multiple selection scenarios and can be used individually or in combination. uni-app provides two ways to use checkboxes: single checkbox and checkbox-group.

<template>
  <view>
    <!-- Single usage -->
    <checkbox v-model="checked" /> Agree to the terms
    
    <!-- Group usage -->
    <checkbox-group @change="handleChange">
      <label>
        <checkbox value="apple" /> Apple
      </label>
      <label>
        <checkbox value="banana" /> Banana
      </label>
      <label>
        <checkbox value="orange" /> Orange
      </label>
    </checkbox-group>
  </view>
</template>

<script>
export default {
  data() {
    return {
      checked: false,
      fruits: []
    }
  },
  methods: {
    handleChange(e) {
      this.fruits = e.detail.value
    }
  }
}
</script>

Important properties of the checkbox component:

  • value: Value when selected
  • checked: Whether it is selected
  • disabled: Whether it is disabled
  • color: Color of the selected state

picker Component

The picker component is a selector component that supports multiple modes: normal selector, time picker, date picker, region picker, etc.

<template>
  <view>
    <!-- Normal selector -->
    <picker mode="selector" :range="options" @change="handlePickerChange">
      <view>Current selection: {{selectedOption}}</view>
    </picker>
    
    <!-- Date picker -->
    <picker mode="date" :value="date" start="2020-01-01" end="2025-12-31" @change="handleDateChange">
      <view>Select date: {{date}}</view>
    </picker>
  </view>
</template>

<script>
export default {
  data() {
    return {
      options: ['Option 1', 'Option 2', 'Option 3'],
      selectedOption: '',
      date: '2023-01-01'
    }
  },
  methods: {
    handlePickerChange(e) {
      this.selectedOption = this.options[e.detail.value]
    },
    handleDateChange(e) {
      this.date = e.detail.value
    }
  }
}
</script>

Different modes of the picker component:

  • selector: Normal selector
  • multiSelector: Multi-column selector
  • time: Time picker
  • date: Date picker
  • region: Region picker

radio Component

The radio component is used for single selection scenarios and is usually used with radio-group.

<template>
  <view>
    <radio-group @change="handleRadioChange">
      <label>
        <radio value="male" /> Male
      </label>
      <label>
        <radio value="female" /> Female
      </label>
    </radio-group>
    <view>Current selection: {{gender}}</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      gender: ''
    }
  },
  methods: {
    handleRadioChange(e) {
      this.gender = e.detail.value
    }
  }
}
</script>

Important properties of the radio component:

  • value: Value when selected
  • checked: Whether it is selected
  • disabled: Whether it is disabled
  • color: Color of the selected state

switch Component

The switch component is a sliding switch used to toggle between two states.

<template>
  <view>
    <switch :checked="isChecked" @change="handleSwitchChange" />
    <view>Current state: {{isChecked ? 'On' : 'Off'}}</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isChecked: false
    }
  },
  methods: {
    handleSwitchChange(e) {
      this.isChecked = e.detail.value
    }
  }
}
</script>

Important properties of the switch component:

  • checked: Whether it is selected
  • disabled: Whether it is disabled
  • color: Color of the switch
  • type: Style type, valid values are switch or checkbox

textarea Component

The textarea component is a multi-line text input component, suitable for scenarios requiring large amounts of text input.

<template>
  <view>
    <textarea v-model="content" placeholder="Please enter content" auto-height />
    <view>Characters entered: {{content.length}}</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      content: ''
    }
  }
}
</script>

Important properties of the textarea component:

  • v-model: Two-way data binding
  • placeholder: Hint text in the input box
  • auto-height: Whether to auto-adjust height
  • maxlength: Maximum input length
  • disabled: Whether it is disabled

slider Component

The slider component is a sliding selector used to select a value within a range.

<template>
  <view>
    <slider :value="sliderValue" min="0" max="100" @change="handleSliderChange" />
    <view>Current value: {{sliderValue}}</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      sliderValue: 50
    }
  },
  methods: {
    handleSliderChange(e) {
      this.sliderValue = e.detail.value
    }
  }
}
</script>

Important properties of the slider component:

  • value: Current value
  • min: Minimum value
  • max: Maximum value
  • step: Step size
  • disabled: Whether it is disabled
  • show-value: Whether to display the current value

form Component

The form component is used to group multiple form components together and submit form data uniformly.

<template>
  <view>
    <form @submit="handleSubmit">
      <view class="form-item">
        <text>Username:</text>
        <input name="username" v-model="formData.username" />
      </view>
      <view class="form-item">
        <text>Password:</text>
        <input name="password" type="password" v-model="formData.password" />
      </view>
      <button form-type="submit">Submit</button>
    </form>
  </view>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    handleSubmit(e) {
      console.log('Form data:', this.formData)
      uni.showToast({
        title: 'Submitted successfully',
        icon: 'success'
      })
    }
  }
}
</script>

<style>
.form-item {
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}
</style>

Important properties of the form component:

  • report-submit: Whether to return formId for sending template messages
  • @submit: Event triggered when the form is submitted
  • @reset: Event triggered when the form is reset

Form Validation

In actual development, form validation is essential. uni-app can implement form validation in various ways.

<template>
  <view>
    <form @submit="handleSubmit">
      <view class="form-item">
        <text>Username:</text>
        <input name="username" v-model="formData.username" />
        <text v-if="errors.username" class="error">{{errors.username}}</text>
      </view>
      <view class="form-item">
        <text>Password:</text>
        <input name="password" type="password" v-model="formData.password" />
        <text v-if="errors.password" class="error">{{errors.password}}</text>
      </view>
      <button form-type="submit">Submit</button>
    </form>
  </view>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        username: '',
        password: ''
      },
      errors: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    validateForm() {
      let isValid = true
      
      if (!this.formData.username) {
        this.errors.username = 'Username cannot be empty'
        isValid = false
      } else {
        this.errors.username = ''
      }
      
      if (!this.formData.password) {
        this.errors.password = 'Password cannot be empty'
        isValid = false
      } else if (this.formData.password.length < 6) {
        this.errors.password = 'Password must be at least 6 characters'
        isValid = false
      } else {
        this.errors.password = ''
      }
      
      return isValid
    },
    handleSubmit(e) {
      if (this.validateForm()) {
        console.log('Form validated, submitting data:', this.formData)
        uni.showToast({
          title: 'Submitted successfully',
          icon: 'success'
        })
      }
    }
  }
}
</script>

<style>
.error {
  color: red;
  font-size: 12px;
  margin-left: 10px;
}
.form-item {
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}
</style>

Custom Form Components

In actual projects, you may need to encapsulate some custom form components. Below is an example of a custom rating component.

<template>
  <view>
    <view class="rating-container">
      <text v-for="i in 5" :key="i" @click="handleRate(i)" 
            :class="['iconfont', i <= rating ? 'icon-star-fill' : 'icon-star']">
      </text>
    </view>
    <input type="hidden" name="rating" :value="rating" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      rating: 0
    }
  },
  methods: {
    handleRate(value) {
      this.rating = value
    }
  }
}
</script>

<style>
.rating-container {
  display: flex;
}
.iconfont {
  font-size: 24px;
  margin-right: 5px;
}
.icon-star-fill {
  color: #f5a623;
}
.icon-star {
  color: #ccc;
}
</style>

Form Data Binding

uni-app provides various data binding methods, with v-model two-way binding being the most commonly used.

<template>
  <view>
    <input v-model="message" placeholder="Please enter content" />
    <view>Entered content: {{message}}</view>
    
    <!-- Using v-model with custom components -->
    <custom-input v-model="customValue" />
    <view>Custom component value: {{customValue}}</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      message: '',
      customValue: ''
    }
  }
}
</script>

For custom components, implementing v-model requires defining the model option:

// Inside the custom component
export default {
  model: {
    prop: 'value',
    event: 'input'
  },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  methods: {
    handleInput(e) {
      this.$emit('input', e.target.value)
    }
  }
}

Form Submission and Reset

The form component supports submission and reset operations, which can be specified via the form-type property on buttons.

<template>
  <view>
    <form @submit="handleSubmit" @reset="handleReset">
      <input name="username" v-model="formData.username" placeholder="Username" />
      <input name="password" type="password" v-model="formData.password" placeholder="Password" />
      
      <button form-type="submit">Submit</button>
      <button form-type="reset">Reset</button>
    </form>
  </view>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    handleSubmit(e) {
      console.log('Submitted data:', this.formData)
    },
    handleReset() {
      this.formData = {
        username: '',
        password: ''
      }
    }
  }
}
</script>

Styling Form Components

Form components in uni-app can be styled using CSS.

<template>
  <view>
    <input class="custom-input" placeholder="Custom styled input" />
    <button class="custom-button">Custom button</button>
  </view>
</template>

<style>
.custom-input {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  margin: 10px 0;
}

.custom-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  margin-top: 10px;
}

.custom-button:active {
  background-color: #3e8e41;
}
</style>

Form Component Performance Optimization

When forms are complex, performance optimization is necessary:

  1. Avoid using complex expressions in templates
  2. Load large forms in steps
  3. Use v-if and v-show appropriately to control component display
  4. Use debounce or throttle for frequently changing data
<template>
  <view>
    <!-- Use v-show instead of v-if to maintain component state -->
    <view v-show="showSection1">
      <!-- Form content -->
    </view>
    
    <!-- Use debounce for input -->
    <input v-model="searchText" @input="debounceSearch" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchText: '',
      debounceTimer: null,
      showSection1: true
    }
  },
  methods: {
    debounceSearch() {
      clearTimeout(this.debounceTimer)
      this.debounceTimer = setTimeout(() => {
        this.doSearch()
      }, 500)
    },
    doSearch() {
      // Actual search logic
    }
  }
}
</script>

Form Components and Backend Interaction

Form data usually needs to be submitted to a backend server, which can be done using the uni.request method.

<template>
  <view>
    <form @submit="handleSubmit">
      <input name="username" v-model="formData.username" />
      <input name="password" type="password" v-model="formData.password" />
      <button form-type="submit">Login</button>
    </form>
  </view>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    handleSubmit() {
      uni.request({
        url: 'https://api.example.com/login',
        method: 'POST',
        data: this.formData,
        success: (res) => {
          if (res.data.success) {
            uni.showToast({ title: 'Login successful' })
          } else {
            uni.showToast({ title: res.data.message, icon: 'none' })
          }
        },
        fail: (err) => {
          uni.showToast({ title: 'Network error', icon: 'none' })
        }
      })
    }
  }
}
</script>

Form Data Persistence

You can use uni.setStorage to temporarily save form data locally.

<template>
  <view>
    <input v-model="draft.title" placeholder="Title" />
    <textarea v-model="draft.content" placeholder="Content"></textarea>
    <button @click="saveDraft">Save draft</button>
    <button @click="loadDraft">Load draft</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      draft: {
        title: '',
        content: ''
      }
    }
  },
  methods: {
    saveDraft() {
      uni.setStorage({
        key: 'formDraft',
        data: this.draft,
        success: () => {
          uni.showToast({ title: 'Draft saved successfully' })
        }
      })
    },
    loadDraft() {
      uni.getStorage({
        key: 'formDraft',
        success: (res) => {
          this.draft = res.data
          uni.showToast({ title: 'Draft loaded successfully' })
        }
      })
    }
  }
}
</script>

Form Component Internationalization

For multilingual applications, form components need to support internationalization.

<template>
  <view>
    <input :placeholder="$t('form.username')" v-model="username" />
    <input :placeholder="$t('form.password')" type="password" v-model="password" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: ''
    }
  }
}
</script>

// Language resource files
// en.json
{
  "form": {
    "username": "Username",
    "password": "Password"
  }
}

// zh-CN.json
{
  "form": {
    "username": "用户名",
    "password": "密码"
  }
}

Form Component Accessibility

To improve accessibility, form components should include appropriate ARIA attributes.

<template>
  <view>
    <label for="username">Username:</label>
    <input id="username" aria-label

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.