天天看點

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>           

複制

Vue之自定義事件應用場景事件綁定原生事件
Vue之自定義事件應用場景事件綁定原生事件
Vue之自定義事件應用場景事件綁定原生事件
Vue之自定義事件應用場景事件綁定原生事件

根據以上代碼,可以得出個事件執行流程,基本上不管什麼自定義事件都是這個流程

  • 子元件某方法
  • this.$emit('event')

  • DOM上

    v-on

    監聽

    event

  • 父元件

    methods

    中的

    callback

在執行個體中子元件已經和它外部完全解耦了。它所做的隻是觸發一個父元件關心的内部事件。

原生事件

如果你想在某個元件的根元素上監聽一個原生事件。可以使用 .native 修飾 v-on 。例如:

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