请查看密码字段。单击更改密码?
按钮时,将显示密码
和确认密码
字段。
下面的代码工作正常,并按照 v-show
的预期验证表单,但在使用 v-if
时不会验证。
我了解 v-show
和 v-if
的作用,以及 data(){}
中的函数,这就是它在 element 中的用法-ui 的文档。这是文档的网址:http://element.eleme.io/#/en-US/component/form#custom-validation-rules
<template lang="pug">
el-dialog( width="600px", title="Users", :visible.sync="dialogVisible")
el-form.demo-ruleForm(:model="editedItem", status-icon, :rules="formRules", ref="userForm", label-width="140px")
el-form-item(label="Name", prop="firstName")
el-input(v-model="editedItem.name", auto-complete="off")
template(v-if="!changePassword")
el-form-item
el-button(@click="changePassword = true") Change Password?
template(v-else)
el-form-item(label="Password", prop="password")
el-input(type="password", v-model="editedItem.password", auto-complete="off")
el-form-item(label="Confirm Password", prop="confirmPassword")
el-input(type="password", v-model="editedItem.confirmPassword", auto-complete="off")
.dialog-footer(slot="footer")
el-button(type="primary", @click="submitForm('userForm')") Save
</template>
<script>
export default {
name: 'dialog-add-edit-user',
props: {
editedItem: Object,
},
data () {
const validatePass = (rule, value, callback) => {
if (value === '') {
callback(new Error('Please input the password'))
} else {
if (this.confirmPassword !== '') {
this.$refs.userForm.validateField('confirmPassword')
}
callback()
}
}
const validatePass2 = (rule, value, callback) => {
if (value === '') {
callback(new Error('Please input the password again'))
} else if (value !== this.editedItem.password) {
callback(new Error('Two inputs don\'t match!'))
} else {
callback()
}
}
return {
formRules: {
password: [
{
validator: validatePass,
trigger: 'blur'
}
],
confirmPassword: [
{
validator: validatePass2,
trigger: 'blur'
}
]
},
dialogVisible: false,
changePassword: false,
editedItem: {
name: '',
password: '',
confirmPassword: ''
}
}
},
methods: {
submitForm (formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
this.$emit('save-item')
console.log('submit!')
} else {
console.log('error submit!!')
return false
}
})
}
}
}
</script>
最佳答案
好的,我想我明白问题所在了。
您的验证已通过,但未检查 name
和password
,仅 passwordChange
.
因此,如果您“...了解 v-show 和 v-if 的作用”,您就会知道当您使用 v-if
时这些元素不存在。/v-else
。它们根据需要添加和删除。
出现此问题的原因是元素库在添加时会经历初始化阶段。稍后使用 $ref
引用该元素。看SubmitForm
,它使用 `this.$refs[formName].validate'
所以当你使用v-if/v-else
时,因为这些元素一开始就不存在,所以它们不会被正确调用。
您有两个选择,要么坚持 v-show
,这应该很容易,或者您可以使用我一直在利用不允许强制手动或自动重新加载的第三方库的 hack。该黑客攻击包括添加 key
到主要元素。所以 html 看起来像这样。
<el-form
class="demo-ruleForm"
:model="editedItem"
status-icon="status-icon"
:key="'form'+changePassword" <--- this is the magic
:rules="formRules"
ref="userForm"
label-width="140px"
>
和哈巴狗
el-form.demo-ruleForm(:model="editedItem", :key="'form'+changePassword", status-icon, :rules="formRules", ref="userForm", label-width="140px")
关于javascript - 如何使 Vue 的 element-ui validateField() 与 v-if 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49520256/