为什么这个 vuelidate 函数不能在设置中工作,而只能在方法之外的方法中工作?
why does this vuelidate function not work within setup, but only outside, within methods?
我正在使用组合 API 的 vuelidate,但我不明白为什么 v$.validate()
在 methods
内,在 setup
之后可以正常工作,但不在 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.
}
}
但是,这不起作用:
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
}
}
这有点麻烦,因为我为 axios 调用使用了一个可组合项,其中 state
是一个参数。将整个代码放在一个地方会更容易。
useVuelidate
returns a computed
, so you need to use .value
when accessing any of it's properties, like $error
, $validate
inside the setup
function.
In the template it is unwrapped for you.
我正在使用组合 API 的 vuelidate,但我不明白为什么 v$.validate()
在 methods
内,在 setup
之后可以正常工作,但不在 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.
}
}
但是,这不起作用:
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
}
}
这有点麻烦,因为我为 axios 调用使用了一个可组合项,其中 state
是一个参数。将整个代码放在一个地方会更容易。
useVuelidate
returns acomputed
, so you need to use.value
when accessing any of it's properties, like$error
,$validate
inside thesetup
function.
In the template it is unwrapped for you.