Vue的自定義事件
- 子組件中,選擇click或其他原生事件來封裝
- 父組件中,使用v-on/@系結事件監聽器
自定義事件是自定義組件才有的,
自定義事件其實就是封裝DOM原生事件,如何封裝?——就是在原生事件的回呼中發射(emit)一個自定義事件,
下面就是具體操作:
子組件中,選擇click或其他原生事件來封裝
// 自定義組件boringButton.vue
<template>
<button v-on:click="incrementHandler">{{ counter }}</button>
</template>
<script>
export default {
name: 'boring-button',
methods: {
incrementHandler: function () {
this.counter += 1;
this.$emit('increment');
}
}
}
</script>
父組件中,使用v-on/@系結事件監聽器
// 參考boringButton.vue的檔案
<template>
<!-- 注意increment的大小寫和emit的保持一致,要一毛一樣才行 -->
<boringButton @increment='incrementTotal'></boringButton>
</template>
<script>
methods: {
incrementTotal: function () {
console.log('I increment the boringButton!');
}
}
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/199109.html
標籤:其他
上一篇:從后臺拿到token后存到headers中方法 AXios的方法
下一篇:Android studio ERROR: Failed to resolve: androidx.appcompat:appcompat:1.1.0 問題解決方法
