uniapp vue3 表单写法
时间: 2023-11-11 12:06:21 浏览: 158
vue3-form-usage:使用vue3的表单用法
在uniapp中,可以使用Vue3的Composition API来编写表单。具体步骤如下:
1. 在setup函数中定义表单数据和表单验证规则:
```
import { ref } from 'vue'
export default {
setup() {
const formData = ref({
username: '',
password: ''
})
const rules = {
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' }
]
}
return {
formData,
rules
}
}
}
```
2. 在模板中使用uni-form组件来渲染表单:
```
<template>
<view>
<uni-form :model="formData" :rules="rules">
<uni-form-item label="用户名" prop="username">
<uni-input v-model="formData.username" placeholder="请输入用户名"></uni-input>
</uni-form-item>
<uni-form-item label="密码" prop="password">
<uni-input v-model="formData.password" type="password" placeholder="请输入密码"></uni-input>
</uni-form-item>
<uni-form-item>
<uni-button type="primary" @click="submitForm">提交</uni-button>
</uni-form-item>
</uni-form>
</view>
</template>
```
3. 在methods中定义submitForm方法来提交表单:
```
import { ref } from 'vue'
import { useForm } from '@ant-design-vue/use'
export default {
setup() {
const formData = ref({
username: '',
password: ''
})
const rules = {
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' }
]
}
const { validate } = useForm(formData, rules)
const submitForm = () => {
validate().then(() => {
// 表单验证通过,可以提交表单
}).catch(() => {
// 表单验证不通过,不提交表单
})
}
return {
formData,
rules,
submitForm
}
}
}
```
阅读全文