VUE 兄弟通信(除了父子就是兄弟)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>兄弟组件通信</title>
</head>
<body>
<div  id="app">
    <brother></brother>
    <hr>
    <sbrother></sbrother>
</div>
<template  id="brother">
    <div>
        哥哥
         {{msg}}
        <button @click="gchan">哥哥</button>
    </div>
</template>
<template  id="sbrother">
    <div>
        弟弟
        {{msg}}
    {{change()}}
    </div>
</template>
<script src="vue.js"></script>
<script>
    let  bus=new Vue();
    Vue.component("brother",{
        template:"#brother",
        data(){
            return {
                msg:"我是你哥哥"
            }
        },
        methods:{
            gchan(){
                bus.$emit("suibian",this.msg)
            }
        }
    });
    Vue.component("sbrother",{
        template:"#sbrother",
        data(){
            return {
                msg:"我是你弟弟"
            }
        },
        created(){
        },
        mounted(){
            bus.$on("suibian",(val)=>{
                this.msg=val;
            })
        },
        methods:{
            change(){
            }
        }
    })
    new Vue({
    }).$mount("#app")
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/Le_OOP/article/details/81745692
今日推荐