将 Vuelidate 实例作为模态数据传递使其未定义

Passing Vuelidate instance as modal data makes it undefined

我在表单组件中有一个 Vuelidate 实例。另一个父组件包含它并需要通过双向模型绑定访问它的验证器实例。

奇怪的问题是,如果我在子组件中为模型值设置 Vuelidate 实例,那么它在父组件中设置为未定义。如果将其封装在 {validator} 之类的对象中,则数据会成功传递给父对象。

父组件

<template>
  <MyForm v-model:modelValidator="formValidator" />
  <button @click="log" >Log Model Value</button>
</template>

<script>
export default { 
  setup(props) {   
    const formValidator = ref();

    const log= () => {
      //logs undefined if vuelidate is assigned directly in the child component
      console.log(formValidator.value)
    };

  return {log}
  }
}
</script>

子组件

<script>
export default {
  props: {
    modelValue: null,
    modelValidator: null
  },
  emits: ["update:modelValue", "update:modelValidator"],
  setup(props, { emit }) {
    const state = computed({
      get: () => props.modelValue,
      set: (value) => emit("update:modelValue", value),
    });
    const modelValidator = computed({
      get: () => props.modelValidator,
      set: (value) => emit("update:modelValidator", value),
    });

   const  validator= useVuelidate({/*Rules...*/}, state);

   //CASE A: If I set directly the validator then parent component model value sets undefined
   modelValidator.value =validator;

   //CASE B: If I set directly the validator enclosed in an object then parent 
   //        component model value sets the expected object with validator. It's OK.
   modelValidator.value ={validator:validator};

}
</script>

由 dobromir-hristov 在 https://github.com/vuelidate/vuelidate/issues/1041

回答

Instead of passing the validator as a prop back to a component, you can rely on our automatic parent-child internal communication.

If a component has useVuelidate called, it will collect all of it's children validation instances. They are not only accessible in the parent, but also augment it's $error and $errors properties, so you can use them as you wish.

Here is an example, using the scopes docs.

https://vuelidate-next.netlify.app/advanced_usage.html#validation-scopes