首页 新闻 赞助 找找看

有点不能理解vue2.0里面的使用v-on绑定自定义事件里面的实例

0
[已解决问题] 解决于 2019-05-14 16:18

  

<div id="counter-event-example">
  <p>{{ total }}</p>
  <button-counter v-on:increment="incrementTotal"></button-counter>
  <button-counter v-on:increment="incrementTotal"></button-counter>
</div>
 
Vue.component('button-counter', {
  template: '<button v-on:click="increment">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1
      this.$emit('increment')
    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
})

 

 

 子组件先触发了increment事件,然后因为这个所以触发了父组件里面的incrementTotal事件?那子组件里面又有点击事件触发increment是怎么回事,还有this.$emit('increment')这个是什么意思啊,懵,请大神指教。

红枣味酸奶的主页 红枣味酸奶 | 菜鸟二级 | 园豆:218
提问于:2017-03-30 09:50
< >
分享
最佳答案
0

this.$emit:通知订阅者。

on:订阅某个事件。

 

v-on:increment="incrementTotal":订阅子组件的increment事件。回掉函数是incrementTotal。

 

Vue.component('button-counter', {
  template: '<button v-on:click="increment">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1
      this.$emit('increment')
    }
  },
})
子组件有个按钮。对子组件的this.counter += 1。并通父组件this.$emit('increment')订阅者。
<button-counter v-on:increment="incrementTotal"></button-counter> 父组件订阅子组件的事件。
事件触发,对父组件this.total += 1
incrementTotal: function () {
      this.total += 1
    }
 
奖励园豆:5
czd890 | 专家六级 |园豆:14292 | 2017-03-30 11:02
其他回答(1)
0

这个没接触过,不懂!帮你顶一下!

初学者2号 | 园豆:22 (初学一级) | 2017-03-30 10:09

哈哈,谢谢

支持(0) 反对(0) 红枣味酸奶 | 园豆:218 (菜鸟二级) | 2017-03-30 10:38
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册