Vue.js 监听和触发事件

原文链接:https://my.oschina.net/MinghanSui/blog/1920363
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue.js 监听和触发事件</title>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
	<div id="counter-event-example">
	  <p>{{total}}</p>
          <!-- 当监听到increment事件时,执行incrementTotal方法 -->
	  <button-counter @increment="incrementTotal"></button-counter>
	  <button-counter @increment="incrementTotal"></button-counter>
	</div>
</div>

<script>
Vue.component('button-counter', {
  template: '<button v-on:click="incrementHandler">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    incrementHandler: function () {
      this.counter += 1
      // 触发父组件的监听事件increment
      this.$emit('increment')
    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
})
</script>
</body>
</html>

 

转载于:https://my.oschina.net/MinghanSui/blog/1920363

展开阅读全文
博主设置当前文章不允许评论。

没有更多推荐了,返回首页