< template> < div> < div v- for = "(formData, index) in forms" : key= "index" > < u- form : model= "formData" : rules= "rules" ref= "formRefs" > < u- form- item label= "用户名" prop= "username" > < u- input v- model= "formData.username" > < / u- input> < / u- form- item> < u- form- item label= "密码" prop= "password" > < u- input type= "password" v- model= "formData.password" > < / u- input> < / u- form- item> < / u- form> < / div> < u- button @click= "submitForm()" > 提交< / u- button> < / div>
< / template> < script setup>
import { reactive, ref } from "vue" ; const forms = reactive ( [ { username : "" , password : "" } , { username : "" , password : "" } ,
] ) ; const formRefs = ref ( [ ] ) ; const rules = { username : [ { required : true , message : "请输入用户名" , trigger : "blur" } ] , password : [ { required : true , message : "请输入密码" , trigger : "blur" } ] ,
} ; const submitForm = ( ) => { if ( formRefs. value?. length) { Promise. all ( formRefs. value?. map ( ( ref ) => ref. validate ( ) ) ) . then ( ( results ) => { console. log ( "验证结果" , results) ; if ( results. some ( ( res ) => ! res) ) { uni. $u. toast ( "请正确填写必填项!" ) ; } else { console. log ( "校验通过" ) } } ) . catch ( ( errors ) => { uni. $u. toast ( "请正确填写必填项!" ) ; } ) ; }
} ;
< / script>