父组件为子组件传递数据(数据校验)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <div id="app">
        <child1-component
        :root-name="name"
        :root-age="age"
        :root-gender="gender"
        :root-marry="marry"
        :root-wechat="wechat"
        :root-hobby="hobby"></child1-component>
    </div>

    <script src="./vue.js"></script>
    <script>

        const app = new Vue({
            el: '#app',
            data: {
                name: '苑文浩',
                age: 20,
                gender: true,
                marry: '已婚',
                wechat: '1271876231873',
                hobby: '学习'
            },
            components: {
                'child1-component': {
                    props: {
                        // 必须要传入,并且数据类型必须是字符串。
                        rootName: {
                            type: String,
                            required: true
                        },
                        // 可以不传递,但是,一旦传递,则数据类型必须是 Number 类型
                        rootAge: Number,
                        // 可以不传递,但是,一旦传递,则数据类型必须是 Boolean 或者 String 类型
                        rootGender: [Boolean, String],
                        // 可以不传递,默认是 '未婚',一旦传递,则数据类型必须是 String 类型
                        rootMarry: {
                            type: String,
                            default: '未婚'
                        },
                        // 可以不传递,默认是 '110',一旦传递,则数据类型必须是 String 类型
                        rootWechat: {
                            type: String,
                            default () {
                                return '110'
                            }
                        },
                        // 可以不传递,一旦传递,数据类型必须是字符串,并且,必须是数组中包含的值。
                        rootHobby: {
                            type: String,
                            // 自定义校验器,如果传入的数据合法,则返回 true,否则返回 false
                            validator (hobby) {
                                return ['吃饭','睡觉','学习'].includes(hobby)
                            }
                        }
                    },
                    data() {
                        return {
                            child1Message: 'child1组件的数据'
                        }
                    },
                    template: `<div>
                    <h2>{{child1Message}}</h2>
                    <h2>{{rootName}}</h2>
                    <h2>{{rootGender}}</h2>
                    <h2>{{rootMarry}}</h2>
                    <h2>{{rootWechat}}</h2>
                    <h2>{{rootHobby}}</h2>
                    </div>`
                }
            }
        });

   

    </script>
</body>

</html>
posted @ 2022-10-21 10:42  张尊娟  阅读(20)  评论(0编辑  收藏  举报