對(duì)vue.js中this.$emit的深入理解
對(duì)于vue.js中的this.emit的理解:this.emit(‘increment1',”這個(gè)位子是可以加參數(shù)的”);其實(shí)它的作用就是觸發(fā)自定義函數(shù)。
看例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<script src="vue.js"></script>
<body>
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment1="incrementTotal1"></button-counter>
<button-counter v-on:increment2="incrementTotal2"></button-counter>
</div>
</body>
<script>
Vue.component('button-counter', {
template: '<button v-on:click="increment">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
increment: function () {
this.counter += 1;
this.$emit('increment1',"這個(gè)位子是可以加參數(shù)的");//觸發(fā)自定義increment1的函數(shù)。此處的increment1函數(shù)就是 incrementTotal1函數(shù)。
// this.$emit('increment2'); //此時(shí)不會(huì)觸發(fā)自定義increment2的函數(shù)。
}
}
});
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal1: function (e) {
this.total += 1;
console.log(e);
},
incrementTotal2: function () {
this.total += 1;
}
}
})
</script>
</html>
對(duì)上面的例子進(jìn)行進(jìn)一步的解析:
1、首先看 自定組件button-counter ,給其綁定了方法 :increment;
2、點(diǎn)擊button時(shí)會(huì)執(zhí)行函數(shù) increment,increment中有 this.$emit(‘increment1',”這個(gè)位子是可以加參數(shù)的”);
3、當(dāng)increment執(zhí)行時(shí),就會(huì)觸發(fā)自定函數(shù)increment1,也就是incrementTotal1函數(shù);
4、而increment執(zhí)行時(shí)沒有觸發(fā)自定義函數(shù)increment2,所以點(diǎn)擊第二個(gè)按鈕不執(zhí)行incrementTotal2的函數(shù)。
以上這篇對(duì)vue.js中this.$emit的深入理解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
基于Vue3定制復(fù)雜組件滾動(dòng)條的實(shí)現(xiàn)
這篇文章主要介紹了如何利用vue3定制復(fù)雜組件的滾動(dòng)條,文中通過示例代碼講解詳細(xì),需要的朋友們下面就跟隨小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
詳解項(xiàng)目升級(jí)到vue-cli3的正確姿勢
這篇文章主要介紹了詳解項(xiàng)目升級(jí)到vue-cli3的正確姿勢,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-01-01
vue3界面使用router及使用watch監(jiān)聽router的改變
vue2中使用router非常簡單,但是vue3中略微有些改變,通過本文講解下他的改變,對(duì)vue3?watch監(jiān)聽router相關(guān)知識(shí)感興趣的朋友一起看看吧2022-11-11
vue的props實(shí)現(xiàn)子組件隨父組件一起變化
這篇文章主要為大家詳細(xì)介紹了vue的props如何實(shí)現(xiàn)子組件隨父組件一起變化,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10
vue中v-model指令與.sync修飾符的區(qū)別詳解
本文主要介紹了vue中v-model指令與.sync修飾符的區(qū)別詳解,詳細(xì)的介紹了兩個(gè)的用法和區(qū)別,感興趣的可以了解一下2021-08-08

