组件通信 eventtBus

平级组件的通信 一个全局发布订阅模式,它是挂载到全局的

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>组件通信 &bus</title>
    <script src="./node_modules/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
       <children1></children1>
       <children2></children2>
    </div>
</body>
<script>
    //发布订阅模式
    //适合简单的数据流
     Vue.prototype.$bus = new Vue();
    Vue.component('children1',{
     template:`<div><span>children1</span></div>`,
     mounted() {
         this.$bus.$on('',(food)=>{
             console.log(food)
         }) 
     },
   })
   Vue.component('children2',{
     template:`<div><span>children2</span></div>`,
     mounted() {
         this.$bus.$emit('','月饼')
     },
   })
   let  vm = new Vue({
         el:'#app',
   })
   //hello
</script>
</html>

 

posted @ 2019-09-18 10:22  1点  阅读(267)  评论(0编辑  收藏  举报