zoukankan      html  css  js  c++  java
  • 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

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

     

  • 相关阅读:
    硬盘的结构和介绍,硬盘MBR详细介绍(超详细彩图)
    websocket协议学习
    Qt4可以使用trUtf8函数,其内容可以是中文,也可以是F硬编码
    QString转换为LPTSTR(使用了reinterpret_cast,真是叹为观止,但是也开阔了思路),三篇文章合起来的各种转换方法
    系统高可用
    Visual Studio
    管道是如何建立起来的?
    CLR和.Net对象
    任务调度
    路由与控制器
  • 原文地址:https://www.cnblogs.com/shuen/p/9056559.html
Copyright © 2011-2022 走看看