You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中结合vue-facing-decorator使用Vuelidate的方法

在Vue3中结合vue-facing-decorator使用Vuelidate的解决方案

1. 安装适配依赖

确保安装支持Vue3的Vuelidate包和最新版的vue-facing-decorator:

npm install @vuelidate/core @vuelidate/validators vue-facing-decorator
# 或使用yarn
yarn add @vuelidate/core @vuelidate/validators vue-facing-decorator

2. 组件内的正确实现方式

Vue3版本的Vuelidate采用组合式API设计,不再支持Vue2中通过@Component装饰器配置validations的写法,需按以下方式实现:

<script lang="ts">
import { Component, Vue } from 'vue-facing-decorator';
import { useVuelidate } from '@vuelidate/core';
// 导入需要的验证规则
import { required, minLength } from '@vuelidate/validators';

@Component
export class Calendario extends Vue {
  // 定义表单字段
  eventTitle = '';
  eventDate = '';

  // 声明验证规则对象
  validations = {
    eventTitle: {
      required,
      minLength: minLength(3)
    },
    eventDate: { required }
  };

  // 初始化Vuelidate实例并挂载到组件的$v属性上
  $v = useVuelidate();

  created() {
    // 现在可正常调用Vuelidate的方法
    // this.$v.$touch();
    // this.$v.$reset();
  }

  handleSubmit() {
    // 触发表单所有字段的验证
    this.$v.$touch();
    // 检查验证状态
    if (this.$v.$invalid) {
      console.log('表单验证未通过');
      return;
    }
    // 执行提交逻辑
    console.log('表单提交成功');
  }
}
export default Calendario;
</script>

3. 模板中使用验证状态

在模板里可直接通过$v访问各字段的验证状态:

<template>
  <form @submit.prevent="handleSubmit">
    <div>
      <label>事件标题</label>
      <input v-model="eventTitle" type="text">
      <span v-if="$v.eventTitle.$error">
        <span v-if="$v.eventTitle.required">标题不能为空</span>
        <span v-if="$v.eventTitle.minLength">标题不能少于3个字符</span>
      </span>
    </div>
    <div>
      <label>事件日期</label>
      <input v-model="eventDate" type="date">
      <span v-if="$v.eventDate.$error">日期不能为空</span>
    </div>
    <button type="submit">提交</button>
  </form>
</template>

关键说明

  • Vue3的Vuelidate不再支持组件选项配置validations,必须通过useVuelidate()创建验证实例。
  • 将useVuelidate()的返回值赋值给组件的$v属性,即可在组件方法和模板中沿用Vue2的方式访问验证对象及方法($touch()、$reset()、$invalid等)。
  • 需保证vue-facing-decorator版本≥2.0.0,该版本开始全面支持Vue3类组件语法。

内容的提问来源于stack exchange,提问作者Natan Veloso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 15:01:08