vue.js - 使用 Vuelidate 从父组件验证子组件中的表单输入字段

标签 vue.js vuejs2 vue-component vuelidate

我是 Vue Js 和 Vuelidate 的新手。刚刚尝试验证来自父组件的表单输入字段,如下所示:https://github.com/monterail/vuelidate/issues/333

父组件中的子组件:

<contact-list ref="contactList" :contacts="contacts" @primaryChanged="setPrimary" @remove="removeContact" @ready="isReady => readyToSubmit = isReady"/>

在 child 的方法:
computed: {
    ready() {
        return !this.$v.email.$invalid;
    }
},
watch: {
    ready(val) {
        this.$emit('ready', val);
    }
},

methods: {
    touch() {
        this.$v.email.$touch();
    }
}

我正在从父级调用 touch() 方法,如下所示:
submit() {
            this.$refs.contactList.touch();
        },

但我收到此错误:
Error in event handler for "click": "TypeError: this.$refs.contactList.touch is not a function".
有任何想法吗?谢谢。

最佳答案

我面临同样的问题。这是我为解决它所做的。

  • 创建了一个全局事件池。我可以在哪里使用 $emit 发出事件我的 child 可以使用 $on 订阅或 $once并使用 $off 取消订阅.在您的 app.js 内粘贴下面的代码。下面是事件池操作的列表。
  • 发出: this.$eventPool.$emit()
  • 在: this.$eventPool.$on()
  • 关闭:this.$eventPool.$off()
  • 一次: this.$eventPool.$once()
  • Vue.prototype.$eventPool = new Vue();
  • 在我的子组件中,我创建了一个 watch$v如下。它将表单的状态发送到父组件。
  • watch: {
        "$v.$invalid": function() {
          this.$emit("returnStatusToParent", this.$v.$invalid);
        }
      }
    
  • 现在在您的父组件中处理如下状态。
  • <ChildComponent @returnStatusToParent="formStatus =>isChildReady=formStatus"></ChildComponent>
  • 现在要向用户显示正确的错误,我们将 $touch child 表格。为此,我们需要在上面创建的事件池中发出一个事件,我们的 child 将订阅该事件。

  • 家长:
    this.$eventPool.$emit("touchChildForm");
    child :
     mounted() {
        this.$eventPool.$on("touchChildForm", () => {
          this.$v.$touch();
          this.$emit("returnStatusToParent", this.$v.$invalid);
        });
      },
      destroyed() {
        this.$eventPool.$off("touchChildForm", () => `{});`
      }
    

    希望能帮助到你 :)

    关于vue.js - 使用 Vuelidate 从父组件验证子组件中的表单输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53628450/

    相关文章:

    javascript - 将 VueJs 模态组件添加到 Laravel 模板

    javascript - Vue.js - 当子组件在 <transition> 内时无法访问 this.$parent

    vue.js - 重置为vuejs中的初始数据,但仅限于部分值

    javascript - Vue - 调度完成后调用 store getter?

    javascript - Vuejs 组件等待 facebook sdk 加载

    javascript - 如何更新 vueJs 数组列表的特定行?

    vuejs2 - Vue.js - 父 <-> 插槽通信

    javascript - 在 Vuejs 中渲染输入字段

    css - 根据值更改 Vue Element UI 表格单元格样式

    Vue.js Vuex 如何正确使用 store.watch() 方法?