先贴官网实例:
<template><view class=""><u-form :model="form" ref="uForm"><u-form-item label="姓名" prop="name"><u-input v-model="form.name" /></u-form-item><u-form-item label="简介" prop="intro"><u-input v-model="form.intro" /></u-form-item></u-form><u-button @click="submit">提交</u-button></view>
</template><script>
export default {data() {return {form: {name: '',intro: '',},rules: {name: [{ required: true, message: '请输入姓名', // 可以单个或者同时写两个触发验证方式 trigger: ['change','blur'],}],intro: [{min: 5, message: '简介不能少于5个字', trigger: 'change'}]}};},methods: {submit() {this.$refs.uForm.validate(valid => {if (valid) {console.log('验证通过');} else {console.log('验证失败');}});}},// 必须要在onReady生命周期,因为onLoad生命周期组件可能尚未创建完毕onReady() {this.$refs.uForm.setRules(this.rules);}
};
</script>
按这个来会发现,有校验,但是不会打印“验证通过”或是“验证失败”
下面是我简陋的修改版:
submit() {this.$refs.uForm.validate(valid => {}).then(res => {// 返回的res.data 已经进行JSON.parseconsole.log("验证成功");console.log(res);}).catch(err => {console.log("验证失败");console.log(err);})}