[英]How to validate all fields in one Vue-component with another components together (using Vee-Validate)?
我使用 Vue.js 2.5.13
+ Vee-Validate 2.0.3
。 我的代碼結構是:
./component-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>
./component-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
)制作,非常適合在一個地方驗證所有這些。
您可以通過 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.