自定义组件校验-使用vee-validate

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

 

转载于:https://my.oschina.net/huangweiindex/blog/1564112

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值