vee-validate 官网:http://vee-validate.logaretm.com/
直接上实例
子组件:
(src/components/input/CustomInput.vue)
<template>
<input type="text" name="custom" v-model="innerValue" placeholder="请输入内容" @input="$emit('input',$event.target.value)" >
</template>
<script>
export default {
data: () => ({
innerValue: ''
})
}
</script>
注意:
1,data中一定要有代表文本框内容的字段(最简单的方法是使用v-model),将被父组件的 data-vv-value-path使用
2,在@input事件中派发input event
父组件:
(src/components/TestValidate.vue)
<template>
<div style="margin-left: 600px;" class="columns is-multiline">
<div class="column is-12">
<custom-input v-validate="'required|email'" data-vv-value-path="innerValue" data-vv-name="custom" :has-error="errors.has('custom')">
</custom-input>
<span v-show="errors.has('custom')" style="color:red;" class="help is-danger">{{ errors.first('custom') }}</span>
<br>
<button @click="validate" type="button" class="button is-primary">Validate All</button>
</div>
</div>
</template>
<script>
import CustomInput from '@/components/input/CustomInput'
import Vue from 'vue';
import VeeValidate from 'vee-validate';
Vue.use(VeeValidate, {
// events: 'blur',
// 指定locale为中文
locale: 'zh_CN'
});
import cn from 'vee-validate/dist/locale/zh_CN'
// 默认是en,这里添加中文的lang包
VeeValidate.Validator.addLocale(cn)
export default {
name: 'component-example',
components: {
CustomInput
},
methods: {
validate() {
this.$validator.validateAll().then((result) => {
// eslint-disable-next-line
// alert(`Validation Result: ${result}`);
});
}
}
}
</script>
注意:
1,如果custom input组件在内容更新时不派发input事件(
this.$emit('input',val)
),那么将不会实时(或失去焦点)校验
2,VeeValidate中中配置不能设置,inject false,
使用组合组件时,inject 必须为true