代码
<el-dialog v-dialogDrag width="800px" :visible.sync="dialogVisible" @close="reset" >
<el-form :model="deviceBox" :rules="rules" ref="deviceBox" label-width="100px">
<el-form-item label="数量" prop="quantity">
<el-input v-model.number="deviceBox.quantity"></el-input>
<!-- <el-input v-model="deviceBox.quantity"></el-input> -->
</el-form-item>
</el-form>
<div slot="footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="submitForm">确 定</el-button>
</div>
</el-dialog>
rules: {
quantity: [
{type: 'number', message: '数量必须为数字值'}
]
}
reset () {
this.deviceBox = {
'quantity': 1
}
}
注意
数字类型的验证需要在 v-model 处加上 .number 的修饰符,这是 Vue 自身提供的用于将绑定值转化为 number 类型的修饰符。
现象
当输入’1test’时,校验通过,提交保存强制转化为1,
当输入’test1’时,校验不通过,提示数量必须为数字值。
问题
当输入’1test’时,校验通过,提交保存强制转化为1。
但是关闭对话框,再打开时,输入框默认显示的不是1而是’1test’,猜测是el-form有缓存导致。
因为虽然每次关闭对话框执行了reset(),但是给deviceBox.quantity设置的值还是1,和’1test’强制转换成的1一致,估计el-form就没有刷新当前的输入框。
结论
在重置函数reset()中设置deviceBox.quantity为任意数值N,输入’Ntest’时都会出现如上所述问题。
只有改reset()强制重置deviceBox.quantity变量为空即可,因为输入框无法输入’‘会提示’数量必须为数字值’:
reset () {
this.deviceBox = {
'quantity': ''
}
}