Vue之自定义事件

应用场景

我们都知道父组件想给子组件传递东西很简单,props里直接放就完事了,而子组件想给父组件传东西就不是那么容易,这个时候就可以利用自定义事件来满足我们的需求。

事件绑定

自定义组件能使子组件事件触发父组件中的动作。

父组件是如何监听事件呢?

使用指令v-on:event-name="callback"监听。

子组件如何触发事件呢? 

调用this.$emit(eventName)

来个小例子 

采用菜鸟教程的小例子点击一下直接跳转 菜鸟教程在线编辑器


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
    <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>
</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
      this.$emit('increment')
    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
})
</script>
</body>
</html>

 

 

 

根据以上代码,可以得出个事件执行流程,基本上不管什么自定义事件都是这个流程

  • 子组件某方法
  • this.$emit('event')
  • DOM上v-on监听event
  • 父组件methods中的callback

 在实例中子组件已经和它外部完全解耦了。它所做的只是触发一个父组件关心的内部事件。

原生事件

如果你想在某个组件的根元素上监听一个原生事件。可以使用 .native 修饰 v-on 。例如:

<my-component v-on:click.native="doTheThing"></my-component>

おすすめ

転載: blog.csdn.net/nxcniuxiangchen/article/details/121670045
おすすめ