vue 在 props 中定义多属性对象,语法如下

例如定义 formValidate 对象,且 formValidate 中含有属性 city 和 name,默认 city 和 name 都是空

formValidate: {
    type: Object,
    default: ()=>{
        return {
            city: '',
            name: ''
        }
    }
}

测试

下面以View UI (iview)中的组件 Form 表单作为子组件进行演示

子组件 Userinfo 代码

<template>
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
        <FormItem label="Name" prop="name">
            <Input v-model="formValidate.name" placeholder="Enter your name"></Input>
        </FormItem>
        
        <FormItem label="City" prop="city">
            <Select v-model="formValidate.city" placeholder="Select your city">
                <Option value="beijing">北京</Option>
                <Option value="nanjing">南京</Option>
                <Option value="shenyang">沈阳</Option>
            </Select>
        </FormItem>
       
        <FormItem>
            <Button type="primary" @click="handleSubmit('formValidate')">Submit</Button>
            <Button @click="handleReset('formValidate')" style="margin-left: 8px">Reset</Button>
        </FormItem>
    </Form>
</template>
<script>
    export default {
        props: {
            formValidate: {
                type: Object,
                default: ()=>{
                    return {
                        city: '',
                        name: ''
                    }
                }
            }
        },
        data () {
            return {
                ruleValidate: {
                    name: [
                        { required: true, message: 'The name cannot be empty', trigger: 'blur' }
                    ],
                    city: [
                        { required: true, message: 'Please select the city', trigger: 'change' }
                    ]
                }
            }
        },
        methods: {
            handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.$Message.success('Success!');
                    } else {
                        this.$Message.error('Fail!');
                    }
                })
            },
            handleReset (name) {
                this.$refs[name].resetFields();
            }
        }
    }
</script>

父组件代码

<template>
    <div>
        <Userinfo :formValidate="formValidate"></Userinfo>
    </div>
</template>
<script>
import Userinfo from '@/view/chil/Userinfo';
    export default {
        components: {
            Userinfo
        },
        data () {
            return {
                formValidate: {
                    city: 'beijing',
                    name: '薛宝钗'
                },
            }
        },
        methods: {

        }
    }
</script>

运行效果

 

至此完

Logo

前往低代码交流专区

更多推荐