解决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事件冲突问题就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。