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

Vue3升级Vuelidate v2后v$.$model始终为null的问题

Vuelidate v2中v$对象无$model属性的解决办法

问题根源

Vuelidate v2 对核心API进行了重构,不再默认提供$model属性,这是与v0.x版本的关键差异。

可行解决方案

1. 手动绑定模型对象

将响应式变量包装为reactive对象传入验证器,再手动给v$挂载$model属性,还原v0.x的使用习惯:

<template><input v-model="test"/></template>
<script>
import { useVuelidate } from '@vuelidate/core'
import { required } from '@vuelidate/validators'
import { ref, reactive, defineComponent } from 'vue'

export default defineComponent({
  setup(props, ctx) {
    const test = ref('')
    const model = reactive({ test }) // 用reactive包装成对象
    const v$ = useVuelidate({ test: { required } }, model)

    v$.$model = model // 手动添加$model属性,方便调试

    return {
      v$,
      test,
    }
  }
})
</script>

2. 直接访问字段的value属性

Vuelidate v2中,每个验证字段的value属性对应模型的当前值,可直接访问:

// 单个字段取值
console.log(v$.test.value) // 输出test的当前值

// 批量组装模型对象(多字段场景)
const assembleModel = () => {
  return Object.fromEntries(
    Object.keys(v$)
      .filter(key => !key.startsWith('$'))
      .map(key => [key, v$[key].value])
  )
}
console.log(assembleModel()) // 输出{ test: '' }

3. 启用兼容配置(部分版本支持)

部分Vuelidate v2版本支持通过初始化配置开启$model,可尝试传入第三个配置参数:

const v$ = useVuelidate(
  { test: { required } },
  { test: test },
  { $model: true } // 开启$model属性
)

注:该配置兼容性有限,优先推荐前两种方法。

调试技巧

在Vue DevTools中,可直接查看v$下对应字段(如test)的value属性,替代原$model的调试路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 03:37:34