對vue.js中this.$emit的深入理解
對于vue.js中的this.emit的理解:this.emit(‘increment1',”這個位子是可以加參數(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',"這個位子是可以加參數(shù)的");//觸發(fā)自定義increment1的函數(shù)。此處的increment1函數(shù)就是 incrementTotal1函數(shù)。
// this.$emit('increment2'); //此時不會觸發(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>
對上面的例子進行進一步的解析:
1、首先看 自定組件button-counter ,給其綁定了方法 :increment;
2、點擊button時會執(zhí)行函數(shù) increment,increment中有 this.$emit(‘increment1',”這個位子是可以加參數(shù)的”);
3、當increment執(zhí)行時,就會觸發(fā)自定函數(shù)increment1,也就是incrementTotal1函數(shù);
4、而increment執(zhí)行時沒有觸發(fā)自定義函數(shù)increment2,所以點擊第二個按鈕不執(zhí)行incrementTotal2的函數(shù)。
以上這篇對vue.js中this.$emit的深入理解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue3界面使用router及使用watch監(jiān)聽router的改變
vue2中使用router非常簡單,但是vue3中略微有些改變,通過本文講解下他的改變,對vue3?watch監(jiān)聽router相關知識感興趣的朋友一起看看吧2022-11-11
vue中v-model指令與.sync修飾符的區(qū)別詳解
本文主要介紹了vue中v-model指令與.sync修飾符的區(qū)別詳解,詳細的介紹了兩個的用法和區(qū)別,感興趣的可以了解一下2021-08-08

