1. 概述
老話說的好:努力幫別人解決難題,你的難題也就不難解決了。
言歸正傳,今天我們來聊聊 VUE3 的 click 事件的相關(guān)知識。
2. click 事件
2.1 實現(xiàn)數(shù)字遞減
<body>
<div id="myDiv"></div>
</body>
<script>
const app = Vue.createApp({ // 創(chuàng)建一個vue應(yīng)用實例
data() {
return {
num : 5
}
},
methods : {
decr() {
if(this.num <= 0) {
alert("庫存為0,無法購買")
return;
}
this.num-- ;
},
},
template : `
<div>
商品庫存剩余 {{num}} 件
<button @click="decr">購買</button><br>
</div>
`
});
const vm = app.mount('#myDiv'); // 綁定id為 myDiv 的元素
該例中,每點(diǎn)一次按鈕,商品庫存都會減 1

image
2.2 事件方法中獲取 event 對象
decr(event) {
console.info(event);
console.info(event.target);
if(this.num <= 0) {
alert("庫存為0,無法購買")
return;
}
this.num-- ;
},
方法中可以獲取 event 對象,從中可以獲取一些事件信息

image
2.3 事件方法中增加參數(shù)
methods : {
decr(n) {
if(this.num < 2) {
alert("庫存不足,無法購買")
return;
}
this.num -= n;
},
},
template : `
<div>
商品庫存剩余 {{num}} 件
<button @click="decr(2)">購買2件</button><br>
</div>
`
事件方法 decr 中增加了參數(shù) n,依據(jù)參數(shù)進(jìn)行計算

image
2.4 有參事件方法中獲取 event 對象
methods : {
decr(n, event) {
console.info(event);
console.info(event.target);
if(this.num < 2) {
alert("庫存不足,無法購買")
return;
}
this.num -= n;
},
},
template : `
<div>
商品庫存剩余 {{num}} 件
<button @click="decr(2, $event)">購買2件</button><br>
</div>
`

image
2.5 點(diǎn)擊按鈕執(zhí)行多個方法
methods : {
f1() {
alert("f1")
},
f2() {
alert("f2")
},
},
template : `
<div>
<button @click="f1(), f2()">執(zhí)行多個方法</button><br>
</div>
`
2.6 事件冒泡
methods : {
clickDiv() {
alert("div");
},
clickButton() {
alert("button");
}
},
template : `
<div @click="clickDiv">
<button @click="clickButton">事件冒泡</button><br>
</div>
`
點(diǎn)擊按鈕,會先執(zhí)行 button 上的 click 事件,然后執(zhí)行 div 上的 click 事件
2.7 阻止冒泡
template : `
<div @click="clickDiv">
<button @click.stop="clickButton">阻止事件冒泡</button><br>
</div>
`
如果我們希望點(diǎn)擊按鈕時只執(zhí)行按鈕的事件,可以在按鈕上使用 @click.stop 的寫法阻止事件冒泡。
2.8 事件捕獲
template : `
<div @click.capture="clickDiv">
<button @click="clickButton">事件捕獲</button><br>
</div>
`
如果希望先執(zhí)行 div 事件,再執(zhí)行 button 的事件,可以在 div 上使用 @click.capture 的寫法,讓事件由外向內(nèi)執(zhí)行
2.9 事件只執(zhí)行一次
template : `
<div @click.once="clickDiv">
<button @click="clickButton">事件</button><br>
</div>
`
在 div 上使用 @click.once ,這樣 div 的事件,只會被執(zhí)行一次
3. 綜述
今天聊了一下 VUE3 的 click 事件,希望可以對大家的工作有所幫助
歡迎幫忙點(diǎn)贊、評論、轉(zhuǎn)發(fā)、加關(guān)注 :)
關(guān)注追風(fēng)人聊Java,每天更新Java干貨。