子组件给父组件传数据

父组件访问子组件的数据

a)在子组件中使用vm.$emit(事件名,数据)触发一个自定义事件,事件名自定义
b)父组件在使用子组件的地方监听子组件触发的事件,并在父组件中定义方法,用来获取数据
总结:子组件通过events给父组件发送消息,实际上就是子组件把自己的数据发送到父组件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>父子组件及组件间数据传递</title>
    <script src="js/vue.js"></script>
</head>
<body>
    <div id="itany">
        <my-hello></my-hello>
    </div>
    
    <template id="hello">
        <div>
            <h3>我是hello父组件</h3>
            <h3>访问自己的数据:{{msg}},{{name}},{{age}},{{user.username}}</h3>
            <h3>访问子组件的数据:{{sex}},{{height}}</h3>
            <hr>

            <my-world :message="msg" :name="name" :age="age" @e-world="getData"></my-world>
        </div>
    </template>

    <template id="world">
        <div>
            <h4>我是world子组件</h4>
            <h4>访问父组件中的数据:{{message}},{{name}},{{age}},{{user.username}}</h4>
            <h4>访问自己的数据:{{sex}},{{height}}</h4>
            <button @click="send">将子组件的数据向上传递给父组件</button>
        </div>
    </template>

    <script>
        var vm=new Vue({ //根组件
            el:'#itany',
            components:{
                'my-hello':{  //父组件
                    methods:{
                        getData(sex,height){
                            this.sex=sex;
                            this.height=height;
                        }
                    },
                    data(){
                        return {
                            msg:'网博',
                            name:'tom',
                            age:23,
                            user:{id:9527,username:'唐伯虎'},
                            sex:'',
                            height:''
                        }
                    },
                    template:'#hello',
                    components:{
                        'my-world':{ //子组件
                            data(){
                                return {
                                    sex:'male',
                                    height:180.5
                                }
                            },
                            template:'#world',
                                                                        methods:{
                                send(){
                                    // console.log(this);  //此处的this表示当前子组件实例
                                    this.$emit('e-world',this.sex,this.height); //使用$emit()触发一个事件,发送数据
                                }
                            }
                        }
                    }
                }
            }
        }); 
    </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/wspblog/p/9988731.html