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

Nuxt中如何通过自定义Vuelidate函数访问组件实例方法

问题原因

你遇到的报错主要来自三个错误用法:

  • 校验函数内部调用数组length时误写为方法形式length(),实际length是数组原生属性不需要加括号
  • validations配置直接写为静态对象,没有用函数返回对象的形式,导致Vuelidate无法正确绑定组件实例上下文
  • 计算属性中手动给自定义校验器传参的操作不符合规则,Vuelidate会自动给校验函数注入当前校验值和组件实例vm,不需要主动传参,手动传参会覆盖默认注入逻辑反而导致报错

修正后的完整代码

1. 自定义校验函数调整

const legalActiveSquare = (square, vm) => { 
  // 去掉length后的括号
  return vm.getLegalMoves(square).length > 0 
};

const legalTargetSquare = (targetSquare, vm) => { 
  // 直接通过vm取activeSquare的值即可
  return vm.getLegalMoves(vm.activeSquare).includes(targetSquare) 
};

2. validations配置调整

将静态对象改为函数返回对象的形式,确保上下文正确绑定:

validations() {
  return {
    activeSquare: { required, squareRegex, legalActiveSquare },
    targetSquare: { required, squareRegex, legalTargetSquare },
  }
},

3. 错误提示计算属性调整

不需要手动调用校验函数传参,直接取校验结果的布尔值即可:

computed: {
  activeSquareErrors () {
    const errors = [];
    if (!this.$v.activeSquare.$dirty) return errors
    !this.$v.activeSquare.required && errors.push('必填')
    !this.$v.activeSquare.squareRegex && errors.push('格式应为e4或E4这类棋格格式')
    // 直接判断校验状态即可,不需要手动传参调用
    !this.$v.activeSquare.legalActiveSquare && errors.push('当前棋格没有合法走法')
    return errors
  },
  // 目标棋格错误提示同理
  targetSquareErrors () {
    const errors = [];
    if (!this.$v.targetSquare.$dirty) return errors
    !this.$v.targetSquare.required && errors.push('必填')
    !this.$v.targetSquare.squareRegex && errors.push('格式应为e4或E4这类棋格格式')
    !this.$v.targetSquare.legalTargetSquare && errors.push('目标棋格不在合法走法范围内')
    return errors
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:15:04