vue全局自定义指令-元素拖拽的实现代码
- 作者: LOVE语诺
- 来源: 51数据库
- 2021-08-11
小白我用的是vue-cli的全家桶,在标签中加入v-drap则实现元素拖拽, 全局指令我是写在main.js中
vue.directive('drag', {
inserted: function (el) {
el.onmousedown=function(ev){
var disx=ev.clientx-el.offsetleft;
var disy=ev.clienty-el.offsettop;
document.onmousemove=function(ev){
var l=ev.clientx-disx;
var t=ev.clienty-disy;
el.style.left=l+'px';
el.style.top=t+'px';
};
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
};
};
}
})
后面肯定要补充放大缩小功能,和把定位,宽度信息保留到vuex中的state中
ps:下面看下面板拖拽之vue自定义指令,具体内容如下所述:
前言
在指令里获取的this并不是vue对象,vnode.context才是vue对象,一般来说,指令最好不要访问vue上的data,以追求解耦,但是可以通过指令传进来的值去访问method或ref之类的。
vue指令
官方文档其实已经解释的蛮清楚了,这里挑几个重点的来讲。
1 arguments
el: 当前的node对象,用于操作dom
binding:模版解析之后的值
vnode: vue 编译生成的虚拟节点,可以在上面获取vue对象
oldvnode: 使用当前指令上一次变化的node内容
2。 生命周期
bind: 初始化的时候调用,但这时候node不一定渲染完成
inserted: 被绑定元素插入父节点时调用,关于dom操作尽量在这里用
update:就是内部this.update时会触发这里
面板拖拽逻辑
使用relative,舰艇event上的clientx和clienty鼠标距离页面的位置来改变面板的top和left。
涉及属性
offsetleft:距离参照元素左边界偏移量
offsettop:距离参照元素上边界偏移量
clientwidth:此属性可以返回指定元素客户区宽度
clientheight: 此属性可以返回指定元素客户区高度
clientx:事件被触发时鼠标指针相对于浏览器页面(或客户区)的水平坐标
clienty: 事件被触发时鼠标指针相对于浏览器页面(或客户区)的垂直坐标
onmousedown:鼠标按下事件
onmousemove: 鼠标滑动事件
onmouseup: 鼠标松开事件
实现代码
<div v-drag="'refname'"></div>
在绑定的组件上使用,value非必选项,不挑就默认是基于document的移动
directives: {
drag: {
// 使用bind会有可能没有渲染完成
inserted: function(el, binding, vnode) {
const _el = el; //获取当前元素
const ref = vnode.context.$refs[binding.value]; // 判断基于移动的是哪一个盒子
const masternode = ref ? ref : document; // 用于绑定事件
const masterbody = ref ? ref : document.body; // 用于获取高和宽
const mgl = _el.offsetleft;
const mgt = _el.offsettop;
const maxwidth = masterbody.clientwidth;
const maxheight = masterbody.clientheight;
const elwidth = _el.clientwidth;
const elheight = _el.clientheight;
let positionx = 0,
positiony = 0;
_el.onmousedown = e => {
//算出鼠标相对元素的位置,加上的值是margin的值
let disx = e.clientx - _el.offsetleft + mgl;
let disy = e.clienty - _el.offsettop + mgt;
masternode.onmousemove = e => {
//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = e.clientx - disx;
let top = e.clienty - disy;
// 绑定的值不能滑出基于盒子的范围
left < 0 && (left = 0);
left > (maxwidth - elwidth - mgl) && (left = maxwidth - elwidth - mgl);
top < 0 && (top = 0);
top > (maxheight - elheight - mgt) && (top = maxheight - elheight - mgt);
//绑定元素位置到positionx和positiony上面
positionx = top;
positiony = left;
//移动当前元素
_el.style.left = left + "px";
_el.style.top = top + "px";
};
// 这里是鼠标超出基于盒子范围之后再松开,会监听不到
document.onmouseup = e => {
masternode.onmousemove = null;
document.onmouseup = null;
};
};
}
}
}
总结
以上所述是小编给大家介绍的面板拖拽之vue自定义指令实例详解,希望对大家有所帮助
