VUE:组件与组件之间的通信

91 阅读2分钟

一,父组件向子组件传值:props

首先,准备一个父组件:father,和一个子组件:child.

<body>
    <div id="app">
        <father></father>
    </div>
    <!-- 父组件 -->
    <template id="tplFather">
        <div>
            <h1>这是父组件</h1>
            <child></child>
        </div>
    </template>

    <!-- 子组件 -->
    <template id="tplChild">
        <div>

        </div>
    </template>

    <script src="./js/vue.js"></script>
    <script>
        new Vue({
            el:'#app',
            components:{
                //父组件
                father:{
                    template:'#tplFather',
                    data(){
                        return {
                            msg:'父组件的msg'
                        }
                    },
                    components:{
                        //子组件
                        child:{
                            template:'#tplChild',
                        }
                    }
                }
            }
        })
    
    </script>
</body>

现在需要把父组件的msg,传给子组件。

1.在子组件中,定义一个props,存放一个属性‘msg’.

child:{
        template:'#tplChild',
        props:['msg'],
    }

2.在父组件模板的子组件中添加该props属性,属性值是父组件的msg

<!-- 父组件 -->
    <template id="tplFather">
        <div>
            <h1>这是父组件</h1>
            <!--这里添加属性-->
            <child :msg="msg"></child>
        </div>
    </template>

3.现在可以在子组件中使用数据msg,像普通data数据那样使用。

<!-- 子组件 -->
    <template id="tplChild">
        <div>
            <p>父组件传来: {{msg}}</p>
        </div>
    </template>

二,子组件向父组件传值:$emit

同样准备上面两个组件,父组件:father,子组件:child.

子组件向父组件传递数据,需要用到自定义事件,这里用click事件举例,也可以用别的事件。

1.在子组件中,定义一个按钮,准备点击事件,并绑定一个事件函数。

<!-- 子组件 -->
<template id="tplChild">
    <div>
        <button @click="sendMsg">向父组件发送数据</button>
    </div>
</template>

2.在子组件的methods中,定义点击事件的函数。

//子组件
child:{
    template:'#tplChild',
    data(){
        return {
            sonMsg:'子组件的msg'
        }
    },
    methods:{
        // 点击按钮事件
        sendMsg(){
            // 第一个参数:自定义事件名,第二个参数:传送的数据
            this.$emit('getmsg',this.sonMsg);
        }
    }
}

3.在父组件模板的子组件标签中,设置自定义事件。(注意自定义事件的事件名不要用驼峰式命名,可以用全小写,或者‘-’连接单词)

<!-- 父组件 -->
<template id="tplFather">
    <div>
        <h1>这是父组件</h1>
        <!-- 子组件的事件名=“父组件的事件名” -->
        <!-- 父组件的事件用来接收数据 -->
        <child @getmsg="getval"></child>
    </div>
</template>

4.父组件通过自定义函数getval接收数据。

//父组件
father:{
    template:'#tplFather',
    data(){
        return {
            sonMsg:''
        }
    },
    methods:{
        // 参数data就是子组件传过来的数据
        getval(data){
            this.sonMsg = data;
        }
    },
}

5.可以在父组件中正常使用接收的数据了。

<!-- 父组件 -->
<template id="tplFather">
    <div>
        <h1>这是父组件</h1>
        <!--这里显示子组件传来的数据-->
        <p>子组件传来:{{sonMsg}}</p>
        <child @getmsg="getval"></child>
    </div>
</template>

以上是两种组件间的通信方式。