// Vue 3 Validator 示例代码
// 首先安装 vee-validate 库
// npm install @vee-validate/vue @vee-validate/rules
<template>
<form @submit="onSubmit">
<div>
<label for="email">Email:</label>
<input id="email" v-model="values.email" name="email" type="email" />
<p v-if="errors.email">{{ errors.email }}</p>
</div>
<div>
<label for="password">Password:</label>
<input id="password" v-model="values.password" name="password" type="password" />
<p v-if="errors.password">{{ errors.password }}</p>
</div>
<button type="submit">Submit</button>
</form>
</template>
<script>
import { useForm, useField } from '@vee-validate';
import * as yup from 'yup';
export default {
setup() {
// 定义表单验证规则
const validationSchema = yup.object({
email: yup.string().required().email(),
password: yup.string().required().min(8),
});
// 初始化表单
const { handleSubmit, errors, values } = useForm({
validationSchema,
});
// 获取字段
const { value: email } = useField('email');
const { value: password } = useField('password');
// 提交表单处理函数
const onSubmit = handleSubmit((values) => {
console.log('Form submitted:', values);
// 这里可以添加提交表单的逻辑,例如发送到服务器
});
return {
values,
errors,
onSubmit,
};
},
};
</script>
@vee-validate/vue
和 @vee-validate/rules
,这两个库提供了表单验证的功能。useForm
和 useField
来管理表单状态和字段。validationSchema
,使用 yup
来定义验证规则。handleSubmit
函数用于处理表单提交,并在验证通过后执行指定的逻辑。这样就可以实现一个简单的带有验证功能的 Vue 3 表单。
上一篇:vue style
下一篇:vue electron
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站