【19】vue.js — 父子组件

来源:互联网 发布:龙卷风软件 编辑:程序博客网 时间:2024/06/07 07:19

父子组件

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>        <script type="text/javascript" src="js/vue.js" ></script>    </head>    <body>        <div id="box">            <aaa>            </aaa>        </div>    </body>    <script>        var vm = new Vue({            el: '#box',            data: {            },            components: {                //父组件                'aaa': {                    //使用子组件                    template: '<h2>我是aaa组件</h2><bbb></bbb>',                    //子组件                    components: {                        'bbb': {                            template: '<h3>我是bbb组件</h3>'                        }                    }                }            }        });    </script></html>

vue父子组件

子组件使用父组件数据

vue默认情况下,子组件没法访问父组件数据的,我们需要借助组件的props属性来绑定数据,使用props时注意html转js命名转换是使用驼峰转换的。

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>        <script type="text/javascript" src="js/vue.js" ></script>        <style>        </style>    </head>    <body>        <div id="box">            <aaa>            </aaa>        </div>        <template id="aaa">            <span>我是父级 -> {{msg}}</span>            <bbb @child-msg="get"></bbb>        </template>        <template id="bbb">            <h3>子组件 ---> </h3>            <input type="button" value="send" @click="send" />        </template>    </body>    <script>        var vm = new Vue({            el: '#box',            data:{            },            components:{                'aaa': {                    data() {                        return {                            msg: 111,                            msg2: '我是父组件的数据'                        }                    },                    template: '#aaa',                    methods: {                        get(msg) {                            this.msg = msg;                        }                    },                    components: {                        'bbb': {                            data() {                                return {                                    a: '我是子组件的数据'                                }                            },                            template: '#bbb',                            methods: {                                send() {                                    alert("子组件点击了");                                    //点击按钮,触发注册在子组件上面的'child-msg'方法                                    this.$emit('child-msg',this.a);                                }                            }                        }                    }                }            }        });    </script></html>

点击【子组件】中的按钮,然后调用【子组件】触发函数$emit到【父组件】方法中,以此方式将【子组件数据】传递到【父组件】中。

父组件调用子组件数据前

父组件调用子组件数据后

原创粉丝点击