非父子組件之間的通訊

A組件給B組件傳數據:
    A發送數據:
       var Event_z = new Vue();
       Event_z.$emit('data-a',this.a);
    B接收數據:
    mounted(){
                    Event_z.$on('data-a',a =>{
                        this.c=a;
                    })

必須是箭頭函數html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.js"></script>

</head>

<body>
<div id="app">
<l-a></l-a>
<l-b></l-b>
<l-c></l-c>
</div>
<template id="la">
    <div>
    <h1>la: {{a}}</h1>
        <button @click="atoc">點擊發送</button>
        </div>
</template>
<template id="lb">
    <h2>lb: {{b}}</h2>
</template>
<template id="lc">
    <h3>lc:{{c}}</h3>
</template>
</body>

<script>
    var Event_z = new Vue();
    new Vue({
        el: '#app',
        data:{

        },
        components:{
            'l-a':{
                template:'#la',
                data:function () {
                    return {
                        a:"zheshi A"
                    }
                },
                methods:{
                    'atoc':function () {
                        Event_z.$emit('data-a',this.a);
                        console.log("發送成功")
                    }
                }
            },
            'l-b':{
                template: '#lb',
                data:function () {
                    return {
                        b:"zheshi B"
                    }
                }
            },
            'l-c':{
                template: '#lc',
                data:function () {
                    return {
                        c:"4"
                    }
                },
                mounted(){
                    Event_z.$on('data-a',a =>{
                        this.c=a;
                        console.log('接收成功')
                    })
                }
            }
        }
    })



</script>
</html>
相關文章
相關標籤/搜索