vue長按事件和點擊事件沖突的解決
長按事件和點擊事件沖突的解決
使用場景
在使用vue做移動端開發(fā)時,遇到了長按事件和點擊事件沖突的問題。
具體需求
點擊標(biāo)簽時選中標(biāo)簽,再次點擊時取消選擇,因標(biāo)簽名稱過長,長按標(biāo)簽使用tooltip顯示完整標(biāo)簽名稱。
代碼說明
長按是用touchstart事件和touchend事件來實現(xiàn)的。在touchstart事件里使用setTimeout,時間設(shè)置為長按生效的時間就可以了,下面上代碼。
HTML部分
關(guān)于這里的.prevent修飾符,是用來阻止默認(rèn)動作。但這里我試過,不加在電腦端運(yùn)行時會有異常,手機(jī)端沒有影響,最好還是加上吧。
? ? <div v-for="(item, index) in List" class="flex a-center j-center" >
? ? ? ? ? ?<van-tag ? v-if="!item.selected"
? ? ? ? ? ?@touchstart.prevent="goTouch(item.name)" ?
? ? ? ? ? ?@touchend.prevent="outTouch(index)"
? ? ? ? ? ? >
? ? ? ? ? ? <span >{{ item.name }}</span>
? ? ? ? ? ? </van-tag>
? ? ? ??
? ? ? ? ? ? <van-tag v-if="item.selected" ? color="blue"?
? ? ? ? ? ? ?@touchstart.prevent="goTouch(item.name)"
? ? ? ? ? ? ?@touchend.prevent="outTouch(index)"?
? ? ? ? ? ? ?>
? ? ? ? ? ? <span>{{ item.name }}</span>
? ? ? ? ? ? </van-tag>
? ? </div>JS部分
當(dāng)點擊標(biāo)簽時,timer的值不為0,執(zhí)行單次點擊事件,長按一秒時將timer設(shè)置為0,則只執(zhí)行長按事件。這樣就解決了長按事件和點擊事件的沖突。
data(){
?return{
?timer:0
?}
},
methods:{
//touchstart 事件
goTouch(v) {
? ? ? this.timer = setTimeout(() => {
? ? ? ? this.timer = 0
? ? ? ? //執(zhí)行長按事件
? ? ? }, 1000);
? ? ? return false
?},
?
?//touchend事件
? ? outTouch(index) {
? ? ? clearTimeout(this.timer);
? ? ? if(this.timer!=0){
? ? ? //執(zhí)行單次點擊事件
? ? ? }
? ? ? return false
?}
}vue web端長按事件,解決和click沖突
? <div ? ? ? ? ? class="main_content" ? ? ? ? ? @mousedown="loopZoom()" ? ? ? ? ? @mouseup="clearLoopZoom()" ? ? ? ? ? @click="handlerZoom()" ? ? ? ? > ? ? ? ? ? 測試長按 ? ? ? ? </div>
? ?handlerZoom() {
? ? ? ? if (this.flag) {
? ? ? ? ? console.log('執(zhí)行click事件')
? ? ? ? }
? ? ? ? this.flag = false
? ? },
? ? loopZoom() {
? ? ? console.log("長按開始咯")
? ? ? this.firstTime = new Date().getTime()
? ? ? this.timeOut = setTimeout(() => {
? ? ? console.log("長按事件")
? ? ? }, 800);
? ? },
? ? clearLoopZoom() {
? ? ? console.log("長按結(jié)束咯")
? ? ? this.lastTime=new Date().getTime()
? ? ? if (this.lastTime - this.firstTime < 100) {
? ? ? ? ? this.flag=true
? ? ? ? }
? ? ? clearTimeout(this.timeOut);
? ? ? this.timeOut = "";
? ? ? clearInterval(this.setIntervals);
? ? ? this.setIntervals = "";
? ? },以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue?前端路由工作原理hash與history的區(qū)別
這篇文章主要介紹了Vue?前端路由工作原理hash與history的區(qū)別,文章圍繞主題展開vue-router的工作原理的簡單介紹,感興趣的朋友可以學(xué)習(xí)一下2022-07-07
vue-router如何實時動態(tài)替換路由參數(shù)(地址欄參數(shù))
這篇文章主要介紹了vue-router如何實時動態(tài)替換路由參數(shù)(地址欄參數(shù)),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
vue elementui簡易側(cè)拉欄的使用小結(jié)
這篇文章主要介紹了vue elementui簡易側(cè)拉欄的使用,增加了側(cè)拉欄,目的是可以選擇多條數(shù)據(jù)展示數(shù)據(jù),本文通過示例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-06-06
基于Vue.js與WordPress Rest API構(gòu)建單頁應(yīng)用詳解
這篇文章主要介紹了基于Vue.js與WordPress Rest API構(gòu)建單頁應(yīng)用詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09

