我使用Vue.js 2.5.13
+ Vee-Validate 2.0.3
。我的代码结构是:
./组件one.vue :
<template>
<div>
<input type="text" name="input_one" id="input_one"
v-model="input_one"
v-validate="'required'"
:class="{'is-danger': errors.has('input_one')}" />
<component-two></component-two>
<button @click="submitForm">Submit!</button>
</div>
</template>
<script>
import Vue from 'vue'
import VeeValidate from 'vee-validate'
import ComponentTwo from './component-two.vue'
Vue.use(VeeValidate, {
events: 'input|blur'
})
export default {
name: "component-one",
components: {
ComponentTwo
},
data() {
return {
input_one: '',
}
},
methods: {
submitForm: function () {
// Validate before submit form
this.$validator.validateAll().then((result) => {
if (result) {
alert('From Submitted!')
return
}
alert('Correct them errors!')
})
}
}
}
</script>
./组件two.vue :
<template>
<div>
<input type="text" name="input_two" id="input_two"
v-model="input_two"
v-validate="'required'"
:class="{'is-danger': errors.has('input_two')}" />
</div>
</template>
<script>
export default {
name: "component-two",
data() {
return {
input_two: ''
}
}
}
</script>
当我点击ComponentTwo
中的button @click="submitForm"
时,如何验证来自ComponentOne
的字段(用于保存此组件中的所有表单数据)。
我有一个巨大的形式,由类似的小Vue组件(都在ComponentOne
收集)制作,非常适合在一个地方验证所有这些。
答案 0 :(得分:0)
您可以通过vue引用在组件上手动触发validateAll(),例如:
父级组件
<template>
<div>
<input type="text" name="input_one" id="input_one"
v-model="input_one"
v-validate="'required'"
:class="{'is-danger': errors.has('input_one')}" />
<component-two ref="validateMe"></component-two>
<button @click="submitForm">Submit!</button>
</div>
</template>
<script>
import Vue from 'vue'
import VeeValidate from 'vee-validate'
import ComponentTwo from './component-two.vue'
Vue.use(VeeValidate, {
events: 'input|blur'
})
export default {
name: "component-one",
components: {
ComponentTwo
},
data() {
return {
input_one: '',
}
},
methods: {
submitForm: async function () {
// Validate before submit form
const result = await this.$validator.validateAll() && await this.$refs.validateMe.$validator.validateAll()
if (result) {
alert('From Submitted!')
return
}
alert('Correct them errors!')
}
}
}
</script>