为什么这个 vuelidate 函数不能在设置内工作,而只能在方法之外工作?

thi*_*ebo 1 vuelidate vuejs3 vue-composition-api

我正在将 vuelidate 与组合 API 一起使用,但我不明白为什么v$.validate()当我放入 inside methods、 aftersetup而不是 inside 时,它​​可以正常工作setup

所以这有效:

setup() {
  // inspired from 
  // https://vuelidate-next.netlify.app/#alternative-syntax-composition-api
  const state = reactive ({
    // the values of the form that need to pass validation, like:
    name: ''
  })

  const rules = computed (() => {
    return {
      // the validation rules
    }

  const v$ = useVuelidate(rules, state)

  return {
    state,
    v$
  }
},
methods: {
  async submitForm () {
    const result = await this.v$.$validate()
    // either result: validation succeeded : axios post call
    // or failure and error messages show up.
  }
}

Run Code Online (Sandbox Code Playgroud)

但是,这不起作用:

setup() {

  const state = reactive ({
    // the values of the form that need to pass validation, like:
    name: ''
  })

  const rules = computed (() => {
    return {
      // the validation rules
    }

  const v$ = useVuelidate(rules, state)

  const submitForm = async () {
    // **ERROR : Uncaught (in promise) TypeError: v$.$validate is not a function**
    const result = await v$.$validate()
    // either result: validation succeeded : axios post call
    // or failure and error messages show up.
  }

  return {
    state,
    v$,
    submitForm
  }
}

Run Code Online (Sandbox Code Playgroud)

这有点痛苦,因为我对 axios 调用使用了可组合项,其中 astate是一个参数。将整个代码保存在一个地方会更容易。

Mic*_*evý 6

合成API

useVuelidate返回 a ,因此您需要在访问它的任何属性(例如函数内部的)时computed使用。.value$error$validatesetup

在模板中,它已为您展开。