1. 在components里面创建一个公共组件,dragMove.vue
<!-- 拖拽滑动效果 -->
<template>
<div id="item_box" @click="goMove" @touchstart="down" @touchmove="move"
@touchend="end">
//这里注意,我使用了阿里图标,你们使用的话,删除掉写自己的样式就好
<i class="iconfont icon-a-bianlidian2x"></i>
</div>
</template>
<script>
export default {
name: "defaultDrag",
data() {
return {
flags: false,
position: { x: 0, y: 0 },
nx: "",
ny: "",
dx: "",
dy: "",
xPum: "",
yPum: "",
};
},
methods: {
goNext() {
this.$emit("goMove");
},
// 实现移动端拖拽
down() {
let item_box = document.querySelector("#item_box");
this.flags = true;
var touch;
if (event.touches) {
touch = event.touches[0];
} else {
touch = event;
}
this.maxW = document.body.clientWidth - item_box.offsetWidth;
this.maxH = document.body.clientHeight - item_box.offsetHeight;
this.position.x = touch.clientX - item_box.offsetLeft;
this.position.y = touch.clientY - item_box.offsetTop;
this.dx = touch.clientX;
this.dy = touch.clientY;
},
move(event) {
event.preventDefault();
let item_box = document.querySelector("#item_box");
if (this.flags) {
var touch;
if (event.touches) {
touch = event.touches[0];
} else {
touch = event;
}
this.nx = touch.clientX - this.position.x;
this.ny = touch.clientY - this.position.y;
if (this.nx < 0) {
this.nx = 0;
} else if (this.nx > this.maxW) {
this.nx = this.maxW;
}
if (this.ny < 0) {
this.ny = 0;
} else if (this.ny >= this.maxH) {
this.ny = this.maxH;
}
item_box.style.left = this.nx + "px";
item_box.style.top = this.ny + "px";
document.addEventListener(
"touchmove",
function() {
// event.preventDefault()
},
false
);
}
},
//鼠标释放
end() {
this.flags = false;
},
},
};
</script>
<style lang="scss" scoped>
#item_box {
width: 1rem;
height: 1rem;
position: fixed;
z-index: 1000;
bottom: 60px;
right: 0.4rem;
border-radius: 50%;
border: 2px solid #ffffff;
box-shadow: 0 0 0.4rem 2px skyblue;
background: #81f8e8;
display: flex;
justify-content: center;
align-items: center;
.iconfont {
color: orange;
}
}
</style>
2. 然后在你们需要使用拖拽的组件中引入 dragMove.vue子组件 就好
(不要忘记在components中注册子组件哟)
//:goMove是子传夫的事件,不用执行任何步骤,写到methods中就好
<dragMove @goMove="watchCar"></dragMove>
标签:box,vue,ny,event,nx,item,touch,移动,拖拽 From: https://www.cnblogs.com/dreammiao/p/16866913.html