對于vue.js中的this.emit的理解:this.emit(‘increment1',”這個位子是可以加參數(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',"這個位子是可以加參數(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>對上面的例子進(jìn)行進(jìn)一步的解析:
1、首先看 自定組件button-counter ,給其綁定了方法 :increment;
2、點(diǎn)擊button時會執(zhí)行函數(shù) increment,increment中有 this.$emit(‘increment1',”這個位子是可以加參數(shù)的”);
3、當(dāng)increment執(zhí)行時,就會觸發(fā)自定函數(shù)increment1,也就是incrementTotal1函數(shù);
4、而increment執(zhí)行時沒有觸發(fā)自定義函數(shù)increment2,所以點(diǎn)擊第二個按鈕不執(zhí)行incrementTotal2的函數(shù)。
以上這篇對vue.js中this.$emit的深入理解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答