vue長按事件和點擊事件沖突的解決
長按事件和點擊事件沖突的解決
使用場景
在使用vue做移動端開發(fā)時,遇到了長按事件和點擊事件沖突的問題。
具體需求
點擊標簽時選中標簽,再次點擊時取消選擇,因標簽名稱過長,長按標簽使用tooltip顯示完整標簽名稱。
代碼說明
長按是用touchstart事件和touchend事件來實現(xiàn)的。在touchstart事件里使用setTimeout,時間設置為長按生效的時間就可以了,下面上代碼。
HTML部分
關于這里的.prevent修飾符,是用來阻止默認動作。但這里我試過,不加在電腦端運行時會有異常,手機端沒有影響,最好還是加上吧。
? ? <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部分
當點擊標簽時,timer的值不為0,執(zhí)行單次點擊事件,長按一秒時將timer設置為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("長按結束咯") ? ? ? this.lastTime=new Date().getTime() ? ? ? if (this.lastTime - this.firstTime < 100) { ? ? ? ? ? this.flag=true ? ? ? ? } ? ? ? clearTimeout(this.timeOut); ? ? ? this.timeOut = ""; ? ? ? clearInterval(this.setIntervals); ? ? ? this.setIntervals = ""; ? ? },
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Vue?前端路由工作原理hash與history的區(qū)別
這篇文章主要介紹了Vue?前端路由工作原理hash與history的區(qū)別,文章圍繞主題展開vue-router的工作原理的簡單介紹,感興趣的朋友可以學習一下2022-07-07vue-router如何實時動態(tài)替換路由參數(shù)(地址欄參數(shù))
這篇文章主要介紹了vue-router如何實時動態(tài)替換路由參數(shù)(地址欄參數(shù)),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09基于Vue.js與WordPress Rest API構建單頁應用詳解
這篇文章主要介紹了基于Vue.js與WordPress Rest API構建單頁應用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09