• vuejs兄弟通信$emit和$on


    1   vm.$on( event, callback )

      监听当前实例上的自定义事件。事件可以由vm.$emit触发。回调函数会接收所有传入事件触发函数的额外参数.

    2 vm.$emit( event, […args] )

    触发当前实例上的事件。附加参数都会传给监听器回调。

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>Title</title>
     6     <script src="js/vue.js"></script>
     7 </head>
     8 <body>
     9 <!--view-->
    10 <div id="app">
    11     <xiongda></xiongda>
    12     <xionger></xionger>
    13 </div>
    14 <script>
    15     var bus=new Vue();
    16     Vue.component('xiongda',{template:`
    17         <div>
    18         <h3>我是熊大</h3>
    19         <button @click="noticex2">通知熊二</button>
    20 </div>
    21     `,methods:{
    22         noticex2:function () {
    23             //$emit是用于触发定义在熊二<xionger>的自定义事件my-eventX2,'加传递过去的参数'
    24             bus.$emit('my-eventX2','光头强来了');
    25         }
    26     },
    27         mounted:function () {
    28         bus.$on('noticex1',function (msg) {
    29             //用于创建noticex1,可以接收$emit传递的消息
    30             console.log(msg);
    31         })
    32     }
    33     });
    34     Vue.component('xionger',{template:`
    35         <div>
    36         <h3>我是熊二</h3>
    37         <button @click="sendtoda">通知熊大 </button>
    38 </div>
    39     `,
    40         mounted:function () {
    41             //通知熊二的方法写在钩子函数中
    42             //第一个参数表示创建一个自定义事件
    43             bus.$on('my-eventX2',function (msg) {
    44                 console.log(msg);
    45             })
    46         },methods:{
    47         sendtoda:function () {
    48             bus.$emit('noticex1',"熊大,我收到消息了,立马过去!")
    49         }
    50         }
    51 
    52     });
    53     new Vue({ //viewmodel
    54         el: 'div',
    55         data: {msg: 'Hello EN', dd: 'you are welcome!'}//model
    56     });
    57 </script>
    58 </body>
    59 </html>
    View Code

    ==========================全家桶式的兄弟通信过程====================================

     

  • 相关阅读:
    poj 3304线段与直线相交
    poj 1039 几何没思路
    zoj 1010 (线段相交判断+多边形求面积)
    poj 1654 Area (多边形求面积)
    poj 3348--Cows(凸包求面积)
    zoj 2107&&hdu 1007最近点对问题
    Codeforces Round #260 (Div. 2)AB
    MMORPG大型游戏设计与开发(part1 of net)
    MMORPG大型游戏设计与开发(规范)
    MMORPG大型游戏设计与开发(构架)
  • 原文地址:https://www.cnblogs.com/shuen/p/9056559.html
Copyright © 2020-2023  润新知