问题
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