【问题标题】:VInput rules and requirements using extend使用扩展的 VInput 规则和要求
【发布时间】:2021-08-25 08:51:31
【问题描述】:

我正在使用 Vue+Vuetify,我需要重新设计一个自定义选择器组件。

当前代码如下所示:

<template>
  <v-autocomplete
    :id="id"
    v-model="internalValue"
    :clearable="clearable"
    :disabled="disabled"
    :hide-details="hideDetails"
    :label="label"
    :readonly="readonly"
    :required="required"
    :rules="rules"
    :items="items"
    item-value="id"
    item-text="name"
    no-data-text="No data"
  />
</template>

<script>
export default {
  name: 'MyCustomSelector',
  props: {
    value: {
      type: String,
      default: null,
    },
    label: {
      type: String,
      default: '',
    },
    id: {
      type: String,
      default: null,
    },
    required: Boolean,
    clearable: Boolean,
    hideDetails: Boolean,
    disabled: Boolean,
    readonly: Boolean,
  },
  data() {
    return {
      items: [],
      rules: [
        (value) => {
          if (this.required) {
            return !!value || 'This field is empty'
          } else {
            return true
          }
        },
      ],
    }
  },
  apollo: {
    // apollo logic
      ...
      this.items = loadedItems
      ...
  },
  computed: {
    internalValue: {
      get() {
        return this.value
      },
      set(newVal) {
        this.$emit('input', newVal)
      },
    },
  },
}
</script>

如您所见,几乎所有代码都只是一个props 通行证。所以我决定把代码改成:

<script>
import VAutocomplete from 'vuetify/lib/components/VAutocomplete'

export default VAutocomplete.extend({
  name: 'MyCustomSelector',
  props: {
    itemText: {
      type: String,
      default: 'name',
    },
    itemValue: {
      type: String,
      default: 'id',
    },
    rules: {
      type: Array,
      default: () => [
        (value) => {
          if (this.required) {
            return !!value || 'This field is empty'
          } else {
            return true
          }
        },
      ],
    },
    noDataText: {
      type: String,
      default: 'No data',
    },
  },
  apollo: {
    // apollo logic
      ...
      this.cachedItems = loadedItems
      ...
  },
})
</script>

一切都很好,但有一个小问题 - prop rules 无法按我想要的方式工作,因为 this.required 未知。

这个prop取自Validatable mixin,其中字段的值被简单地依次替换为每个rules

问题是,如何在 rule 依赖于 required 字段状态的情况下编写代码?

【问题讨论】:

    标签: javascript vue.js vuetify.js


    【解决方案1】:

    您必须使用传统函数而不是箭头函数,才能获得 道具资料

     rules: {
      type: Array,
      // change to the traditional function
      default: function () {
        return [
          (value) => {
            if (this.required) {
              return !!value || "This field is empty";
            } else {
              return true;
            }
          },
        ];
      },
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 2017-07-08
      • 2020-10-20
      • 2012-12-24
      • 2021-01-31
      • 2017-09-26
      相关资源
      最近更新 更多