vue.js自定义事件如何触发的?

<script type="x/template" id="child-template">
  <input v-model="msg">
  <button v-on:click="notify">Dispatch Event</button>
</script>

<div id="events-example" class="demo">
  <p>Messages: {{ messages | json }}</p>
  <child v-on:child-msg="handleIt"></child>
</div>
<script>
    Vue.component('child', {
      template: '#child-template',
      data: function () {
        return { msg: 'hello' }
      },
      methods: {
        notify: function () {
          if (this.msg.trim()) {
            this.$dispatch('handleIt', this.msg);
            this.msg = ''
          }
        }
      }
    })

    var parent = new Vue({
      el: '#events-example',
      data: {
        messages: []
      },
      events: {
        'handleIt': function (msg) {
          this.messages.push(msg)
        }
      }
    })
</script>

如上代码中,自定义的child-msg事件是如何触发的并最终执行了handleIt函数?

阅读 12.4k
3 个回答

這邊其實並沒有被觸發,因為並沒有名為 child-msg 的事件被 dispatch

v-on:child-msg="handleIt"

真正被觸發的是你寫在這邊的 events

  events: {
    'handleIt': function (msg) {
      this.messages.push(msg)
    }
  }

如果你是想靠 v-on:child-msg="handleIt" 來處理事件的話,你應該是要把 handleIt 放在 methods 裡面,然後 this.$dispatch('child-msg', this.msg) 才對。

這裡我稍稍修改了你的代碼:https://jsfiddle.net/tomoeba/97kmbrye/1/

我觉得代码是不是有点问题?没看到哪里触发child-msg事件啊?

Vue.component('child', {
  template: '#child-template',
  data: function () {
    return { msg: 'hello' }
  },
  methods: {
    notify: function () {
      if (this.msg.trim()) {
        this.$dispatch('child-msg', this.msg);//这里应该改成child-msg吧,否则代码就真的理解不了了
        this.msg = ''
      }
    }
  }
})

当你点击button的时候执行了buttonclick事件,然后执行了notify方法,然后在notify方法里面dispatch了你自定义的handleIt事件,也就是说是依赖buttonclick事件
可以参考下这里:http://cn.vuejs.org/api/#vm-dispatch

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题