【问题标题】:Vue - non parent child communicationVue——​​非父子通信
【发布时间】:2018-05-08 13:38:49
【问题描述】:

阅读Vue文档时 Non parent-child communication
为了练习,我尝试构建一个示例以查看它是否有效,以下是我的代码:
我构建了两个组件并尝试在单击时使用 Vue 实例总线将消息从 dudi-station 传输到 dudo-station,但它不起作用。
任何人都可以帮忙吗?谢谢!

Vue.component('dudi-station', {
  template: '<div @click="sentMsg">{{dudiMsg}}</div>',
  data: function() {
    return {
      dudiMsg: 'Dudi!!',
    }
  },
  methods: {
    sentMsg: function() {
      bus.$emit('callout', this.dudiMsg);
    },
  }
});

Vue.component('dudo-station', {
  template: '<div>{{dudoMsg}}</div>',
  data: function() {
    return {
      dudoMsg:'',
    }
  },
  created: function() {
    bus.$on('callout', function(value) {
      this.dudoMsg = value;
      console.log(value);
    });
  }
});

var bus = new Vue();
new Vue({
  el: '#app',
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <dudi-station></dudi-station>
  <dudo-station></dudo-station>
</div>

【问题讨论】:

  • 伤心,还是找不到答案。

标签: javascript vue.js components emit


【解决方案1】:

当在组件中从另一个组件接收消息时,使用箭头函数作为事件处理程序。它将帮助您处理“this”关键字范围。

bus.$on('callout', function(value) {
  this.dudoMsg = value;
  console.log(value);
});

代替这个使用它如下

bus.$on('callout', (value) => {
  this.dudoMsg = value;
  console.log(value);
});

【讨论】:

    【解决方案2】:

    因为在这个声明中:

    bus.$on('callout', function(value) {
      this.dudoMsg = value;
    

    this this 并不是你的 vue 实例。 您需要使用箭头函数来确保“this”表示 vue 实例。 如下所示:

    Vue.component('dudi-station', {
      template: '<div @click="sentMsg">{{dudiMsg}}</div>',
      data: function() {
        return {
          dudiMsg: 'Dudi!!',
        }
      },
      methods: {
        sentMsg: function() {
          bus.$emit('callout', this.dudiMsg);
        },
      }
    });
    
    Vue.component('dudo-station', {
      template: '<div>{{dudoMsg}}</div>',
      data: function() {
        return {
          dudoMsg:'',
        }
      },
      created: function() {
        bus.$on('callout',value => {
          this.dudoMsg = value;
          console.log(value);
        });
      }
    });
    
    var bus = new Vue();
    new Vue({
      el: '#app',
    })
    <script src="https://unpkg.com/vue"></script>
    <div id="app">
      <dudi-station></dudi-station>
      <dudo-station></dudo-station>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-21
      • 2019-03-19
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 2017-12-26
      • 2018-12-22
      • 2017-03-14
      相关资源
      最近更新 更多