Vue从子组件向父组件发送消息

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./js/vue.js"></script>
</head>
<body>
    <div id="app">
         <parent></parent>
    </div>
    <script>
        //子组件
        Vue.component('child',{
            template:`
            <div>
                <input type="button" @click="sendData" value="点我发送信息到父组件">
            </div>
            `,
            methods:{
                sendData:function(){
                    this.$emit('myEvent','Hello World! I am Vue!');
                }
            }
        })

        //父组件
        Vue.component('parent',{
            template:`
            <div>
                <child @myEvent="getData"></child>
            </div>
            `,
            methods:{
                getData:function(msg){
                    console.log('收到从子组件的数据:'+msg);
                    this.msg = msg;
                }
            },
            data:function(){
                return {
                    msg:''
                };
            }
        })

 
        var vm = new Vue({
            el:"#app"
        })
    </script>
 
</body>
</html>

  

 

posted @ 2021-02-26 11:45  田野与天  阅读(363)  评论(0编辑  收藏  举报