解决方法:
1.html部分,添加ref="Uform",
2.js部分,添加
onReady(){
this.$nextTick(() => {
this.$refs.form.setRules(this.rules);
});
}
3.如果还不行,报错:Cannot read property 'setRules' of undefined"。这是因为表单使用了v-for,将v-for改为v-show即可!
上代码:
<template>
<view>
<view @click="handleResetPwd()">修改密码</view>
<!-- 修改密码框弹窗 -->
<view class="prompt-box" v-show="isHidden">
<u-form :model="form" ref="form" >
<u-form-item label="旧密码" prop="OldPwd" border-bottom="true" >
<u-input v-model="form.OldPwd" border="none" inputAlign="right" placeholder="请填写旧密码" type="password" />
</u-form-item>
<u-form-item label="新密码" prop="NewPwd" border-bottom="true">
<u-input v-model="form.NewPwd" border="none" inputAlign="right" placeholder="请填写新密码" type="password" />
</u-form-item>
<u-form-item label="确认密码" prop="confirmpwd" border-bottom="true">
<u-input v-model="form.confirmpwd" border="none" inputAlign="right" placeholder="请确定新密码" type="password" />
</u-form-item>
</u-form>
<view class="handle-btn">
<view class="cancel-btn" @click="cancel">
<text>取消</text>
</view>
<view class="confirm-btn" @click="confirm">
<text>确定</text>
</view>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
var equalToPassword = (rule, value, callback) => {
if ( value!==this.form.NewPwd ) {
callback(new Error("两次输入的密码不一致"));
} else {
callback();
}
};
return {
isHidden: false,
form: {
OldPwd: '',
NewPwd: '',
confirmpwd:"",
},
rules: {
OldPwd: [{ required: true, message: "旧密码不能为空", trigger: "blur" }],
NewPwd: [{ required: true, message: "新密码不能为空", trigger: "blur" }, { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }],
confirmpwd: [{ required: true, message: "确认新密码不能为空", trigger: "blur" }, { required: true, validator: equalToPassword, trigger: "blur" }]
}
}
},
methods: {
cancel() {
this.isHidden = false;
},
confirm() {
this.$refs.form.validate().then(res=>{
//发请求,逻辑处理
})
})
},
handleResetPwd() {
this.form.OldPwd="";
this.form.NewPwd = "";
this.form.confirmpwd = "";
this.isHidden = true;
}
},
onReady(){
this.$nextTick(() => {
this.$refs.form.setRules(this.rules);
});
}
}
</script>