vue中$emit與$on

1. 解釋


var Event = new Vue();
// 相當(dāng)于又new了一個vue實例,Event中含有vue的全部方法;
/**
 * 發(fā)送數(shù)據(jù),第一個參數(shù)是發(fā)送數(shù)據(jù)的名稱,接收時還用這個名字接收,
 * 第二個參數(shù)是這個數(shù)據(jù)現(xiàn)在的位置;
 **/
Event.$emit('msg',this.msg);
/**
 * 接收數(shù)據(jù),第一個參數(shù)是數(shù)據(jù)的名字,與發(fā)送時的名字對應(yīng),
 * 第二個參數(shù)是一個方法,要對數(shù)據(jù)的操作
 **/
Event.$on('msg',function(msg){  
   //這里是對數(shù)據(jù)的操作
})

2. 示例:


<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <title>博客園</title>
   <script type="text/javascript" src="js/vue2.0.3.js" ></script>
   <script type="text/javascript">
     // 準(zhǔn)備一個空的實例對象
     var Event = new Vue()
    //A組件
     var A={ 
       template:` 
         <div style="border: 1px solid red; margin-bottom: 10px; width: 300px;">
           <h4>A組件</h4>
           <p>{{a}}</p>
           <input type="button" value="把A數(shù)據(jù)給C" @click="send" />
         </div>
       `, 
       data(){ 
         return {                        
           a:'我是A里面的數(shù)據(jù)'
         } 
       }, 
       methods:{ 
         send(){ // A發(fā)送數(shù)據(jù)
           Event.$emit('a-msg',this.a);
         } 
       } 
     }; 
    //B組件
    var B={ 
      template:`
        <div style="border: 1px solid green; margin-bottom: 10px; width: 300px;">
          <h4>B組件</h4>
          <p>{}</p>
          <input type="button" value="把B數(shù)據(jù)給C" @click="send" />
        </div>
      `, 
      data(){ 
        return { 
          b:'我是B里面的數(shù)據(jù)'
        } 
      }, 
      methods:{ 
        send(){ 
          Event.$emit('b-msg',this.b); 
        } 
      } 
    }; 
    //C組件
    var C={ 
      template:`
        <div style="border: 1px dotted green; margin-bottom: 10px;width: 300px;">
          <h4>我是C組件,我在坐等接收數(shù)據(jù)</h4>
          <p>{{a}}</p>
          <p>{}</p>
        </div>
      `, 
      data(){ 
        return{ 
          a:'', 
          b:''
        } 
      }, 
      mounted(){ //兩種接收的方式
        var _this = this; 
        Event.$on('a-msg',function(a){ 
          _this.a=a; 
        }); 
        Event.$on('b-msg',function(b){ 
          this.b = b; 69                     
        }.bind(this)) 
      } 
    }; 
    window.onload=function(){ 
      new Vue({
        el:'#box', 
        data:{ }, 
        components:{ 
          'com-a':A,
          'com-b':B, 
          'com-c':C
        } 
      })
    } 
  </script>
</head>
<body>
  <div id="box">
    <com-a></com-a>
    <com-b></com-b>
    <com-c></com-c>
  </div>
</body>
</html>

2. 效果圖:


A組件
B組件
C組件
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容