我是 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
内粘贴下面的代码。下面是事件池操作的列表。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/