vue非父子組件間的傳值

2020-3-18    前端達(dá)人

vue非父子組件傳值的基本語法

創(chuàng)建一個(gè)新的vue對(duì)象
var newvue = new Vue()
    
觸發(fā)事件
newvue.$emit('自定義事件名', 參數(shù))
    
監(jiān)聽事件
newvue.on('自定義事件名', 觸發(fā)方法名)
    
銷毀事件
newvue.off('自定義事件名')

案例

放在html頁面上即可顯示,注意要引入vue

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <div>父組件</div>
    <div>
      <button @click='handle'>銷毀事件</button>
    </div>
    <test-tom></test-tom>
    <test-jerry></test-jerry>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    /*
      兄弟組件之間數(shù)據(jù)傳遞
    */
    // 提供事件中心
    var hub = new Vue();

    Vue.component('test-tom', {
      data: function(){
        return {
          num: 0
        }
      },
      template: `
        <div>
          <div>TOM:{{num}}</div>
          <div>
            <button @click='handle'>點(diǎn)擊</button>
          </div>
        </div>
      `,
      methods: {
        handle: function(){
          hub.$emit('jerry-event', 2);
        }
      },
      mounted: function() {
        // 監(jiān)聽事件
        hub.$on('tom-event', (val) => {
          this.num += val;
        });
      }
    });
    Vue.component('test-jerry', {
      data: function(){
        return {
          num: 0
        }
      },
      template: `
        <div>
          <div>JERRY:{{num}}</div>
          <div>
            <button @click='handle'>點(diǎn)擊</button>
          </div>
        </div>
      `,
      methods: {
        handle: function(){
          // 觸發(fā)兄弟組件的事件
          hub.$emit('tom-event', 1);
        }
      },
      mounted: function() {
        // 監(jiān)聽事件
        hub.$on('jerry-event', (val) => {
          this.num += val;
        });
      }
    });
    var vm = new Vue({
      el: '#app',
      data: {

      },
      methods: {
        handle: function(){
          hub.$off('tom-event');
          hub.$off('jerry-event');
        }
      }
    });
  </script>
</body>
</html>
————————————————
版權(quán)聲明:本文為CSDN博主「溫柔的堅(jiān)持」的原創(chuàng)文章,遵循 CC 4.0 BY-SA 版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_43745003/article/details/104919633



分享本文至:

日歷

鏈接

個(gè)人資料

存檔