Vuetify规则函数 - 如何在验证期间访问组件标签?

3
我想在"规则"函数中访问组件的"标签"属性,以便在错误消息中返回本地化的字段名称(已经完成翻译)。
是否有任何方法可以在Vuetify验证调用的规则函数中访问组件的属性?请注意保留html标签。
 <v-text-field
              v-model="obj.count"
              :counter="10"
              :label="this.$locale.get('WidgetCount')"
              :rules="MyRuleFunctionInMyRuleLibrary()"
              name="count"
              required
            ></v-text-field>

可以看到,我的代码中已经有一个本地化字段标签的函数了,我不想重复做两次或者必须指定两次。在"MyRuleLibrary"中,我想要验证规则并正确本地化报告。
我知道我可以在规则函数中直接传递本地化文本关键字,但这样会产生冗余,因为我需要在模板中输入两次,并且我还需要控件/组件的其他属性,所以我宁愿传递或访问组件本身。我已经尝试将“this”传递给组件,例如:
 :rules="MyRuleFunctionInMyRuleLibrary(this, obj.count)"

然而在这种情况下,似乎是整个页面/表单的所有内容,而不是单个组件本身。最初的回答
2个回答

5

使用 TypeScript:

<v-text-field v-model="volume.sizePerInstance" :rules="sizePerInstanceRules" :label="$t('volumes.sizePerInstance') + '  (GB)'" type="number" step="0.01" required min="0" color="#0cc2aa"></v-text-field>

您需要定义一个getter方法来获取组件属性:

get sizePerInstanceRules() {
  return [
    (v: number) => v && v > 0 || 'Max size must be greater than 0',
    (v: any) => v && !isNaN(v) || 'Max size must be a number',
    (v: number) => {
      return this.maxValue >= v || 'Exceeded limit';
    },
  ];
}

0
Vuetify源代码 中,rules 函数只有一个参数(value)。你可以通过将标签定义为数据或计算属性来解决这个问题:
<v-text-field
   v-model="obj.count"
   :counter="10"
   :label="label.count"
   :rules="MyRuleFunctionInMyRuleLibrary()"
   name="count"
   required
 ></v-text-field>

添加标签到数据
 data: () => ({
   label: {
     count: this.$locale.get('WidgetCount')
   }
 })

然后您可以通过this.label.count在验证函数中访问本地化标签。

您可能希望观察区域设置更改以手动更改标签:

 watch: {
   locale: function () {
     this.label = {
       count: this.$locale.get('WidgetCount')
     }
   }
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接