我目前正在尝试使用多个“输入字段”组件创建一个注册表单,一旦按下提交,这些组件都需要验证.当文本内部发生变化时,它们都会自行验证,但我发现很难对所有输入字段进行全局调用以验证所有内容.我想要实现的是:
http://vee-validate.logaretm.com/examples#validate-form但validateAll()方法没有附加到它的字段.
我尝试用email和amp填充validateAll(); confirm_email让我获得了我想要的结果,但错误消息不会显示在字段旁边.
任何帮助将非常感激!
ValidatedInputField.vue:
<template> <div class="form-control" v-bind:class="{ errorPrompt : errors.has(name) }"> <label v-bind:for="name">* {{as}}</label> <input ref="input" v-bind:value="_value" @input="updateValue($event.target.value)" v-validate v-bind:data-vv-rules="rules" v-bind:name="name" /> <span v-bind:v-show="'errors.has(' + name +')'">{{ errors.first(name) }}</span> </div> </template> <script> module.exports = { props: ['name','rules','as','value'],methods: { updateValue(value) { this._value = this.value; this.$emit('input',value); } },computed: { _value() { return this.value; } } }; </script>
Register.vue:
<template> <div class="container"> <Card blueHeader="true" title="Register"> <ValidatedInputField v-model="email" name="email" rules="required|email" as="Email" /> <ValidatedInputField v-model="confirm_email" name="confirm_email" rules="required|email" as="Confirm Email" /> <ValidatedInputField name="company" rules="required" as="Company" /> <InputField name="company_website" as="Company Website" /> <ValidatedInputField name="first_name" rules="required" as="First Name" /> <ValidatedInputField name="last_name" rules="required" as="Last Name" /> <ValidatedInputField name="address_1" rules="required" as="Address 1" /> <InputField name="address_2" as="Address 2" /> <ValidatedInputField name="city" rules="required" as="City" /> <ValidatedInputField name="zip" rules="required" as="Zip/Postal Code" /> </Card> <Card blueHeader="true" title="Terms & Conditions"> <button v-on:click="submitForm()">Submit</button> </Card> </div> </template> <script> import ValidatedInputField from './components/ValidatedInputField'; import InputField from './components/InputField'; module.exports = { methods: { submitForm() { this.$validator.validateAll(); } },data() { return { email: '',confirm_email: '' }; },components: { ValidatedInputField,InputField } }; </script>
解决方法
我不确定我是否正确理解你.但是要全局调用,您必须在单击按钮时发出事件并指示每个模板对该事件执行操作.每个模板的操作应该是’this.$validator.validateAll()’,因为’this’将引用该特定模板.
您可以通过创建命名实例(“总线”)来实现.在创建实例之前创建它.
var bus = new Vue({});
使用它从模板发出:
bus.$emit('validate_all');
并抓住模板:
created: function() { var vm = this; bus.$on('validate_all',function() { vm.$validator.validateAll() }); }