vue長按事件和點擊事件沖突的解決
長按事件和點擊事件沖突的解決
使用場景
在使用vue做移動端開發(fā)時,遇到了長按事件和點擊事件沖突的問題。
具體需求
點擊標簽時選中標簽,再次點擊時取消選擇,因標簽名稱過長,長按標簽使用tooltip顯示完整標簽名稱。
代碼說明
長按是用touchstart事件和touchend事件來實現的。在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中利用simplemde實現markdown編輯器(增加圖片上傳功能)
這篇文章主要介紹了vue中利用simplemde實現markdown編輯器(增加圖片上傳功能),本文通過實例代碼相結合的形式給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-04-04
解決echarts vue數據更新,視圖不更新問題(echarts嵌在vue彈框中)
這篇文章主要介紹了解決echarts vue數據更新,視圖不更新問題(echarts嵌在vue彈框中),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07

