html 布局代码:
<template>
<div class="box">
<!-- 要拖动的盒子 -->
<!-- @mousedown="mousedown" :鼠标的摁下事件="鼠标摁下事件的方法" -->
<!-- :style="point":动态添加样式="定义的属性名" -->
<div class="box-one" @mousedown="mousedown" :style="point"></div>
</div>
</template>
style 样式代码:
<style lang='scss' scoped>
body,
html {
margin: 0;
}
.box {
height: 100vh;
width: 100vw;
background-color: pink;
.box-one {
width: 250px;
height: 250px;
background-color: skyblue;
border-radius: 10px;
// 重点 : 要拖盒子哪个指定位置 或者 哪个盒子 这个 定位就要配合 上面的 定义的 point 属性 去拖拽盒子
position: fixed;
}
}
</style>
script逻辑代码:
<script>
// 初始化 p 的 x轴y轴为0;
const p = { x: 0, y: 0 };
export default {
// 定义数据
data() {
return {
// 定义的动态绑定的属性名;
point: undefined,
};
},
// 生命周期钩子函数 (created)创建后 全局添加方法"mouseup";
created() {
document.addEventListener("mouseup", this.mouseup);
},
// 生命周期钩子函数 (beforeDestroy)销毁前 删除方法"mouseup";
beforeDestroy() {
document.removeEventListener("mouseup", this.mouseup);
},
// 定义方法;
methods: {
// 鼠标摁下方法;
mousedown(e) {
// log(e)查看全局中 当前你鼠标摁下时 有什么属性;
console.log(e);
// 把 offsetX 及 offsetY 赋值给 p的 x轴 和 y轴;
p.x = e.offsetX;
p.y = e.offsetY;
// 动态绑定的数据 等于 本身 或者一个空对象 这里还未改变
this.point = this.point || {};
// 用全局添加 "mousemove" 鼠标移动的方法
document.addEventListener("mousemove", this.mousemove);
},
// 鼠标移动的方法
mousemove(e) {
// log(e)查看全局中 当前你鼠标移动时 有什么属性;
console.log(e);
// 使用$set动态添加(要往哪里添加,"添加的属性",鼠标移动的位置 减去 一开始鼠标点击给赋值给的p的位置 + "拼接px")
this.$set(this.point, "left", e.clientX - p.x + "px");
this.$set(this.point, "top", e.clientY - p.x + "px");
},
// 鼠标抬起的方法
mouseup() {
// 鼠标抬起后 不再调用 mousemove 方法
// 用全局删除 "mousemove" 鼠标移动的方法
document.removeEventListener("mousemove", this.mousemove);
},
},
};
</script>
代码属于小白起步式理解 如有不对请各位大佬指出改正。
我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=ia3inad3d8qa