【问题标题】:Where I should place handler of emit?我应该在哪里放置发射处理程序?
【发布时间】:2017-06-14 16:58:45
【问题描述】:

我有孩子component 并想将一些数据传递给它的父母。 我的子组件如下所示:

// <button @click="sendClick($event)">Send</button>
// ...
data: function (){
    return {
            mycode: ""
        }
    },
    methods: {
        sendClick(e)
        {
            bus.$emit('change', this.mycode);
        }
}

我的父组件看起来:

var app = new Vue({
  el: '#app',
  data: {
    currentView: 'past-form',
    mycode: ''
  },
  methods:
  {
    changeView()
    {
        this.currentView = 'past-form'
        console.log(this.mycode);
    },

  }, 

  created()
  {
        bus.$on('change', function(mycode){
            this.mycode = mycode;

        });
  }

})
  1. 我还没有找到比在 created() 中放置 bus.$on(bus 被全局声明)更好的地方,但文档声明 created() 用于应该在页面已加载。 created() 块有效;我通过将其放入 console.log(this.mycode) 来检查它,但我应该将发射处理程序移到其他地方吗?

  2. 看起来我的代码没有执行mycode: '',因为console.log(this.mycode); 没有打印任何东西。

【问题讨论】:

  • 如果您的孩子是 Vue 的直接孩子,则不需要总线。

标签: vue.js


【解决方案1】:

正如我在评论中提到的,如果您的组件是 Vue 的直接子组件,那么就不需要总线。

也就是说,created 处理程序可以很好地添加您的 bus 事件处理程序。

我预计您遇到的问题是this 问题。尝试将您的处理程序更改为

bus.$on('change', mycode => this.mycode = mycode)

见How to access the correct this inside a callback?

这是一个例子。

console.clear()

const bus = new Vue()

Vue.component("child", {
  template: `<button @click="sendClick($event)">Send</button>`,
  data: function() {
    return {
      mycode: "something"
    }
  },
  methods: {
    sendClick(e) {
      bus.$emit('change', this.mycode);
    }
  }
})

var app = new Vue({
  el: '#app',
  data: {
    currentView: 'past-form',
    mycode: ''
  },
  methods: {
    changeView() {
      this.currentView = 'past-form'
      console.log(this.mycode);
    },

  },

  created() {
    bus.$on('change', mycode => {
        this.mycode = mycode
        this.changeView()
    })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app">
  <child></child>
  Parent mycode: {{mycode}}
</div>

【讨论】:

  • 谢谢,但是我如何更改来自孩子changeView(); 的电话?
  • @user1432751 我不确定我是否理解你。你想在你的事件处理程序中调用changeView 方法吗?
  • 是的,我需要在获取数据后致电changeView。并向用户页面显示“我们得到了您的数据”
  • @user1432751 我更新了上面代码中的处理程序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
  • 1970-01-01
相关资源
最近更新 更多