vue 中跨组件的表单验证
使用的是element写的,里面提供了表单验证。
子组件是这样的
1 <template> 2 <div> 3 <el-form :model="value" ref="numberValidateForm" label-width="100px" class="demo-ruleForm"> 4 <el-form-item 5 label="年龄" 6 prop="age" 7 :rules="[{ required: true, message: '年龄不能为空', trigger: 'change'}]" 8 > 9 <el-input type="age" v-model="value.age" autocomplete="off"></el-input> 10 </el-form-item> 11 </el-form> 12 </div> 13 </template> 14 15 <script> 16 export default { 17 18 props: { 19 value: { 20 type: Object, 21 default () { 22 return {age: ''} 23 } 24 } 25 }, 26 27 methods: { 28 submitForm () { 29 return this.$refs.numberValidateForm.validate() 30 } 31 } 32 } 33 </script>
父组件大概是这样的
<template> <div> <h1>验证表单</h1> <order-input ref="order" v-model="dynamicValidateForm"></order-input> <el-button type="primary" @click="handleClick" > 提交 </el-button> </div> </template> <script> import OrderInput from './OrderInput' export default { components: { OrderInput }, data () { return { dynamicValidateForm: { age: '' } } }, methods: { handleClick () { this.$refs.order.submitForm().then((valid) => { console.log(valid, '提交表单') }, () => { console.log('提交错误') }) } } } </script>