vue项目中实现el-dialog组件可拖拽效果
0. 首先上图,看效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fbbcdcbd71b4d93729e56a761c4a256c.gif)
1. 实现方法
第一步:创建 drag.js文件 实现拖拽源码
export function startDrag(bar, target, callback) {
var params = {
top: 0,
left: 0,
currentX: 0,
currentY: 0,
flag: false,
cWidth: 0,
cHeight: 0,
tWidth: 0,
tHeight: 0
};
bar.style.cursor = 'move';
bar.onmousedown = function (event) {
var e = event ? event : window.event;
params = {
top: target.offsetTop,
left: target.offsetLeft,
currentX: e.clientX,
currentY: e.clientY,
flag: true,
cWidth: document.body.clientWidth,
cHeight: document.body.clientHeight,
tWidth: target.offsetWidth,
tHeight: target.offsetHeight
};
target.style.margin = 0;
target.style.top = params.top + 'px';
target.style.left = params.left + 'px';
if (!event) {
bar.onselectstart = function () {
return false;
}
}
document.onmousemove = function (event) {
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
var e = event ? event : window.event;
if (params.flag) {
var nowX = e.clientX;
var nowY = e.clientY;
var disX = nowX - params.currentX;
var disY = nowY - params.currentY;
var zLeft = 0;
var zTop = 0;
zLeft = parseInt(params.left) + disX;
if (zLeft <= -parseInt(params.tWidth / 2)) {
zLeft = -parseInt(params.tWidth / 2);
}
if (zLeft >= params.cWidth - parseInt(params.tWidth * 0.5)) {
zLeft = params.cWidth - parseInt(params.tWidth * 0.5);
}
zTop = parseInt(params.top) + disY;
if (zTop <= 0) {
zTop = 0;
}
if (zTop >= params.cHeight - parseInt(params.tHeight * 0.5)) {
zTop = params.cHeight - parseInt(params.tHeight * 0.5);
}
target.style.left = zLeft + 'px';
target.style.top = zTop + 'px';
}
if (typeof callback == "function") {
callback(zLeft, zTop);
}
}
document.onmouseup = function () {
params.flag = false;
document.onmousemove = null;
document.onmouseup = null;
};
};
}
第二步:新建 directive.js 文件,创建vue指令配置文件
import { startDrag } from './drag.js'
const draggable = (el, binding) => {
startDrag(el.querySelector('.el-dialog__header'), el.querySelector('.el-dialog'), binding.value);
};
const directives = {
draggable,
};
export default {
install(Vue) {
Object.keys(directives).forEach((key) => {
Vue.directive(key, directives[key]);
});
},
};
第三步:main.js文件中全局引入vue指令
import directive from './utils/directive';
Vue.use(directive)
第四步:使用v-draagble
<el-dialog
v-draggable
title="新增"
:visible.sync="isShow"
@close="handleCancelConfigInfo">
<-- xxxx 弹框内容... -->
</el-form>
<div slot="footer">
<el-button size="small">取消</el-button>
<el-button size="small">保存</el-button>
</div>
</el-dialog>
注意事项
参考资料