Passing Extra Parameters in Vuetify Rules Definition

百般思念 提交于 2020-05-15 09:29:05

问题


My goal is to define my rules once and then reuse them for all of my fields. To do this, I need to pass extra parameters to my rules, like maxlength of 20 on one v-text-field, but a maxlength of 50 on another. From what I see, only the value is getting passed. How can I add extra parameters to my rules?

<template>
  <v-input :rules=[rules.max(20)] v-model="field1" />
  <v-input :rules=[rules.max(50)] v-model="field2" />
</template>
<script>    
  data() {
    rules: {
      max(v, maxnum) { //maxnum is the parameter I want to add so that I can pass different values and reuse the same rule on multiple fields
        return (v || '').length <= maxnum || 'Max exceeded';
      }
    }
  }
</script>

回答1:


You need a function that returns the rule function. The wrapper function should accept any extra params that the rules function doesn't know about (anything other than the value):

<template>
  <v-input :rules=[rules.max(20)] v-model="field1" />
  <v-input :rules=[rules.max(50)] v-model="field2" />
</template>

<script>    
  data() {
    rules: {
      max(maxNum) {
        return v => (v || '').length <= maxNum || 'Max exceeded';
      }
    }
  }
</script>



回答2:


just pass v-model variable as second parameter to your rule.

<template>
  <v-input :rules=[rules.max(20, field1)] v-model="field1" />
  <v-input :rules=[rules.max(50, field1)] v-model="field2" />
</template>

<script>    
  data() {
    rules: {
      max(maxnum, v) { 
        return (v || '').length <= maxnum || 'Max exceeded';
      }
    }
  }
</script>



回答3:


Here is how I was able to solve it

<template>
  <v-input :rules=[rules.max(20)] v-model="field1" />
  <v-input :rules=[rules.max(50)] v-model="field2" />
</template>

<script>    
  data() {
    rules: {
      max(maxNum) {
        return v => (v || '').length <= maxNum || 'Max exceeded';
      }
    }
  }
</script>


来源:https://stackoverflow.com/questions/58883924/passing-extra-parameters-in-vuetify-rules-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!