解決VUE自定義拖拽指令時 onmouseup 與 click事件沖突問題
功能描述:
如圖,右側懸浮菜單按鈕,只支持上下方向拖動,點擊時展開或關閉菜單。
BUG說明:
鼠標上下方向拖拽,如果松開時鼠標位于懸浮按鈕上會默認執行click事件,經驗證,click事件與mouse事件的執行順序為onmousedown =》onmouseup =》onclick,意味著在click事件執行時會與與其相關的mouse事件沖突。
解決方案:
因為click事件執行時間短,所以利用鼠標拖動的時間差作為標志,在拖拽事件中計算鼠標從onmousedown 到onmouseup 所用的時間差,與200ms作比較,作為全局變量。由于vue的directives自定義指令中無法使用this,所以個人采用給元素設置屬性的方式來解決全局變量的存儲問題。
1、自定義上下拖拽指令
說明:指令中沒有this關鍵字,指令中通過el可以直接拿到指令綁定的元素;
directives: { drag: { // 指令的定義 bind: function (el) { let odiv = el; //獲取當前元素 let firstTime=’’,lastTime=’’; odiv.onmousedown = (e) => { document.getElementById(’dragbtn’).setAttribute(’data-flag’,false) firstTime = new Date().getTime(); // 算出鼠標相對元素的位置 let disY = e.clientY - odiv.offsetTop; document.onmousemove = (e) => { // 用鼠標的位置減去鼠標相對元素的位置,得到元素的位置 let top = e.clientY - disY; // 頁面范圍內移動元素 if (top > 0 && top < document.body.clientHeight - 48) {odiv.style.top = top + ’px’; } }; document.onmouseup = (e) => {document.onmousemove = null;document.onmouseup = null;// onmouseup 時的時間,并計算差值lastTime = new Date().getTime();if( (lastTime - firstTime) < 200){ document.getElementById(’dragbtn’).setAttribute(’data-flag’,true)} }; }; } } },
2、懸浮菜單點擊事件中進行驗證。
click(e) { // 驗證是否為點擊事件,是則繼續執行click事件,否則不執行 let isClick = document.getElementById(’dragbtn’).getAttribute(’data-flag’); if(isClick !== ’true’) { return false } if (!localStorage.settings) { return this.$message.error(’請選擇必填項并保存’); } if (this.right === -300) { this.right = 0; this.isMask = true; } else { this.right = -300; this.isMask = false; } },
補充知識:vue 子組件 created 方法不執行問題
近期做了一個項目 里面有一個樹形菜單,將數據寫在 js (死數據)中,所有的東西都能夠正常執行(i 標簽,子節點,父節點),但是當在請求接口文件或者請求后臺數據的時候,發現引入的子組件的created方法不執行,但是點擊父級菜單展開時還是能夠觸發,后來發現 是生命周期的問題,仔細查看一下,后來解決!
解決方法如下:
用watch 檢測一下data的數據變化,created方法既然在點擊的時候執行,所以也必須保留,好啦,就這樣!
以上這篇解決VUE自定義拖拽指令時 onmouseup 與 click事件沖突問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: