【发布时间】:2018-03-27 18:41:55
【问题描述】:
请查看密码字段。 Password 和 Confirm Password 字段在单击 Change Password? 按钮时显示。
以下代码可以正常工作,并按预期使用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>
【问题讨论】:
-
似乎工作正常,jsfiddle.net/fLw3ek9v 你能澄清什么不工作吗?
-
@Daniel,感谢您的帮助。我不确定它是如何为你工作的。另外,我在你的 jsfiddle 中注意到你已经放置了
const validatePass和const validatePass2两次,这与代码工作有关吗?而且,验证消息仅显示Confirm Password。 -
它们不需要出现两次,我只是将它们移出 vue 实例而忘记删除。
标签: javascript vue.js vuejs2 element-ui