【问题标题】:How to validate a custom component with vee-validate 3?如何使用 vee-validate 3 验证自定义组件?
【发布时间】:2021-11-17 04:43:32
【问题描述】:

我正在尝试让 vee-validate 用于自定义组件(我称之为 "DatePickerInput")。
Vee-validate 适用于其他非自定义组件。
DatePickerInput 组件上的v-model 有效(值在父组件中更新)。

问题:没有显示错误消息并且“errors”值保持为空:

<validation-provider
    v-slot="{ errors }"
    :name="$t('StartDate')"
    rules="required">
  <div>{{ errors }}</div>
  <DatePickerInput
      v-model="startDate"
      :label="$t('StartDate')"
      :error-messages="errors" />
</validation-provider>

DatePickerInput 组件是这样创建的(我删除了一些看起来不相关的属性):

<template>
  <v-menu v-model="showMenu">
    <template v-slot:activator="{ on, attrs }">
      <v-text-field
          v-model="date"
          :label="label"
          :error-messages="errorMessages"
          prepend-icon="mdi-calendar"
          v-bind="attrs"
          v-on="on"
          @click:prepend="showMenu = !showMenu"></v-text-field>
    </template>
    <v-date-picker
        :value="isoDate"
        @input="(isoDate) => this.date = isoDate"></v-date-picker>
  </v-menu>
</template>

<script>
export default {
  props: ['value', 'label', 'error-messages'],
  data() {
    return {
      date: this.value,
      showMenu: false,
    }
  },
  computed: {
    isoDate() {
      return new Date(this.date).toISOString().substr(0, 10)
    },
  },
  watch: {
    date: {
      handler(date) { this.handleInput(date) },
    },
  },
  methods: {
    handleInput(e) { this.$emit('input', e) },
  },
}
</script>

为什么不显示错误?

【问题讨论】:

    标签: vuejs2 vue-component vuetify.js vee-validate


    【解决方案1】:

    我发现了我的问题所在。
    vee-validate 中的验证由事件触发。
    重要事件为"blur""change""input"

    在我制作的组件中,来自v-text-field 的事件没有传播到父组件。换句话说:当"blur""change""input"v-text-field 上触发时,我的自定义DatePickerInput 组件上没有触发任何事件。

    为了解决这个问题,我创建了三个方法:

    methods: {
        handleInput(e) {
          this.$emit('input', e)
        },
        handleBlur() {
          this.$emit('blur')
        },
        handleChange(newValue, oldValue) {
          this.$emit('change', newValue, oldValue)
        },
      },
    

    我将这些方法添加到DatePickerInput 组件内的v-text-field 组件中:

          ...
          <v-text-field
              v-model="date"
              :label="label"
              :error-messages="errorMessages"
              prepend-icon="mdi-calendar"
              v-bind="attrs"
              v-on="on"
              @blur="on.blur && on.blur($event); handleBlur($event)"
              @change="on.change && on.change($event); handleChange($event);"
              @click:prepend="showMenu = !showMenu"></v-text-field>
          ...
    

    为了确保v-menu 组件使用的来自"on" 的事件也被触发,我在代码中添加了on.blur &amp;&amp; on.blur($event); 等。我不确定这是否需要,但它有效,所以我很高兴。

    【讨论】:

      猜你喜欢
      • 2019-09-23
      • 2018-11-25
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      相关资源
      最近更新 更多