vuejs子组件向父组件传递数据

 子组件通过$emit方法向父组件发送数据,子组件在父组件的模板中,通过自定义事件接收到数据,并通过自定义函数操作数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript" src="vue.js"></script>
</head>
<body>
    <!-- 子组件向父组件传递数据 -->
    <div id="box">
        <v-parent></v-parent>
    </div>

    <!-- 父组件模板 -->
    <template id="parent">
        <div>
            <span>{{msgParent}}</span>
            <v-child @child-info="get"></v-child>
        </div>
    </template>

    <!-- 子组件模板 -->
    <template id="child">
        <div>
            <button @click="send">send</button>
            <!-- <p>{{msgChild}}</p> -->
        </div>
    </template>
    <script type="text/javascript">
        var app = new Vue({
            el:'#box',
            components:{
                // 父组件
                'v-parent':{    
                    data() {
                        return {
                            msgParent:'hello'
                        }
                    },
                    template:'#parent',
                    methods:{
                        get(msg){
                            this.msgParent = msg 
                        }
                    },
                    // 子组件
                    components:{
                        'v-child':{            
                            data(){
                                return {
                                    msgChild:'child'
                                }
                            },
                            template:'#child',
                            methods:{
                                send(){
                                    this.$emit('child-info',this.msgChild)
                                }
                            }
                        }
                    }
                }
            }
        })
    </script>
</body>
</html>

此时点击子组件模板中的按钮,父模板中的子组件会接受到数据

原文地址:https://www.cnblogs.com/yesyes/p/6619082.html