直接上代码 先在main.js中定义指令
import Vue from "vue";
import App from "./App.vue";
import store from "./store";
Vue.config.productionTip = false;
Vue.directive("drag", {
// bind() {
// },
inserted(el, binding, vnode) {
// console.log(el)
el.style.position = "absolute";
el.style.left = 0;
el.style.top = 0;
let x = 0; // 记录元素拖拽时候的初始x轴位置
let y = 0; // 记录元素拖拽时候的初始y轴位置
el.ontouchstart = function (es) {
// console.log(es)
// el.offsetLeft dom距离左侧的偏移量
// el.offsetTop dom距离顶部的偏移量
x = es.touches[0].pageX - el.offsetLeft;
y = es.touches[0].pageY - el.offsetTop;
document.ontouchmove = function (em) {
let left = em.touches[0].pageX - x + "px";
let top = em.touches[0].pageY - y + "px";
el.style.left = left;
el.style.top = top;
};
};
el.ontouchend = function () {
document.ontouchmove = null;
};
},
// update() {
// },
// componentUpdated() {
// },
// unbind() {
// }
});
new Vue({
store,
render: (h) => h(App),
}).$mount("#app");
然后在需要调用的页面
<template>
<div id="app">
<div class="drag" v-drag></div>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
}
},
methods: {
}
}
</script>
<style>
.drag {
width: 100px;
height: 100px;
background-color: red;
}
</style>