關(guān)于vue.js中this.$emit的理解使用
一、每個 Vue 實例都實現(xiàn)了事件接口
即:
1、使用 $on(eventName) 監(jiān)聽事件
2、使用 $emit(eventName, optionalPayload) 觸發(fā)事件
二、注意事項
1、父組件可以在使用子組件的地方直接用 v-on 來監(jiān)聽子組件觸發(fā)的事件
2、不能用 $on 監(jiān)聽子組件釋放的事件,而必須在模板里直接用 v-on 綁定
三、例子及說明
1、父組件代碼及說明
<template>
? <div>
? ? <p>{{ total }}</p>
? ? <my-button4 @increment1="incrementTotal1"></my-button4> ? ? <!--自定義方法increment1監(jiān)聽子組件觸發(fā)情況-->
? ? <my-button4 @increment2="incrementTotal2"></my-button4> ? ? <!--自定義方法increment2監(jiān)聽子組件觸發(fā)情況-->
? </div>
</template>
<script>
? import myButton4 from './components/myButton4.vue'
? export default{
? ? data(){
? ? ? return{
? ? ? ? ? total:0
? ? ? }
? ? },
? ? methods:{
? ? ? incrementTotal1: function () { ? ? ? ? ? ? ? ? ? ? /*事件incrementTotal觸發(fā)*/
? ? ? ? this.total += 1
? ? ? },
? ? ? incrementTotal2: function () { ? ? ? ? ? ? ? ? ? ?/*事件incrementTota2觸發(fā)*/
? ? ? ? this.total += 2
? ? ? }
? ? },
? ? components:{ ? ? ? ? ? ? ? ? ? ? ? ?/*子組件的實例,要盡量放在最后,不然會出現(xiàn)一些不必要的問題*/
? ? ? myButton4
? ? }
? }
</script>2、子組件代碼及說明
<template>
? ? ? <button @click="incrementCounter">{{counter}}</button> <!--在子組件中創(chuàng)建一個按鈕,創(chuàng)建點擊事件-->
</template>
<script>
? ?export default{
? ? ?data(){
? ? ? ?return{
? ? ? ? ?counter: 0
? ? ? ?}
? ? ?},
? ? ?methods: {
? ? ? ?incrementCounter: function (){
? ? ? ? ?this.counter += 1
? ? ? ? ?this.$emit('increment1') ? ? ? ?/*觸發(fā)自定義事件increment1,也就是父組件中的incrementTotal1事件*/
? ? ? ? ?this.$emit('increment2') ? ? ? ?/*觸發(fā)自定義事件increment2,也就是父組件中的incrementTotal2事件*/
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?/*這兩個事件一次只會觸發(fā)一個,為什么呢?很簡單,因為每次只單擊一個按鈕*/
? ? ? ?}
? ? ?}
? ?}
</script>3、運行截圖
A、開始截圖:

B、點擊第一個按鈕截圖(+1)

C、點擊第二個按鈕截圖(+2)

四、總說明
1、首先看子組件件,按鈕中給其綁定了方法:incrementCounter;
2、點擊button時會執(zhí)行函數(shù) incrementCounter,increment中有 this.$emit(‘increment1)和this.$emit(‘increment2),看點擊的是哪個按鈕就執(zhí)行哪個;
3、當(dāng)incrementCounter執(zhí)行時,就會觸發(fā)自定函數(shù)increment1(點擊第一個按鈕的時候)或者increment(點擊第二個按鈕的時候),也就是incrementTotal1或者incrementTotal2函數(shù);
到此這篇關(guān)于關(guān)于vue.js中this.$emit的理解使用的文章就介紹到這了,更多相關(guān)vue.js this.$emit內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue項目實現(xiàn)背景顏色以及下劃線從左到右漸變動畫效果
這篇文章主要介紹了vue項目實現(xiàn)背景顏色以及下劃線從左到右漸變動畫效果,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08
electron-vue+electron-updater實現(xiàn)自動更新(步驟源碼)
這篇文章主要介紹了electron-vue+electron-updater實現(xiàn)自動更新,步驟源碼包括autoUpdater.js操控更新js文件,main.js也就是package.json內(nèi)的main指向的js文件,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-10-10
Vue中使用vue-count-to(數(shù)字滾動插件)詳細教程
這篇文章主要給大家介紹了關(guān)于Vue中使用vue-count-to(數(shù)字滾動插件)的相關(guān)資料,最近需要開發(fā)一個數(shù)字滾動效果,在網(wǎng)上找到一個關(guān)于vue-countTo的插件,覺得這個插件還不錯,需要的朋友可以參考下2023-09-09

