我试图在一个输入字段更改其值时验证这两个输入字段.这是必需的,因为否则这两个字段之间的验证将无法正常工作.
我创建了一个例子来重现这个问题,html代码应该是不言自明的
<div id="app">
<v-app id="inspire">
<v-text-field
:value="values[0]"
:rules="firstRules"
@input="setFirstValue"
></v-text-field>
<v-text-field
:value="values[1]"
:rules="secondRules"
@input="setSecondValue"
></v-text-field>
</v-app>
</div>
需要注意的是,v-model
是不可能的,因为该组件将值作为prop
接收,并通过发出更新事件将更新后的值传递回父级.
vue实例:
new Vue({
el: '#app',
data () {
return {
values: [5345, 11],
firstRules: [true],
secondRules: [true]
}
},
created: function () {
this.setFirstValue(this.values[0])
this.setSecondValue(this.values[1])
},
computed: {
firstValidation: function () {
return [value => value.length < this.values[1].length || "Must have less characters than second value"]
},
secondValidation: function () {
return [value => value.length > this.values[0].length || "Must have more characters than first value"]
}
},
methods: {
setFirstValue: function (newValue) {
this.values[0] = newValue
this.firstRules = this.validateValue(this.values[0], this.firstValidation)
this.secondRules = this.validateValue(this.values[1], this.secondValidation)
},
setSecondValue: function (newValue) {
this.values[1] = newValue
this.secondRules = this.validateValue(this.values[1], this.secondValidation)
this.firstRules = this.validateValue(this.values[0], this.firstValidation)
},
validateValue: function (value, rules) {
for (const rule of rules) {
const result = rule(value)
if (typeof result === 'string') {
return [result]
}
}
return [true]
}
}
})
在"开始"时,规则返回有效状态,但我想在加载组件时验证这两个字段(创建的钩子?)立即更新此状态.
我必须将验证规则放入计算(computed)属性,因为它们必须访问当前值.否则他们会验证旧的价值观.
每个输入事件将验证这两个字段并更新规则状态.
我在这里创建了一个例子
https://codepen.io/anon/pen/OeKVME?editors=1010
不幸的是,出现了两个问题:
- 字段在开始时不会直接验证
- 将一个输入字段更改为有效状态时,规则仍将返回错误消息
当一个字段更新时,如何为两个字段设置验证?