vue拖拽组件
在vue实现拖拽,经常使用到,所以自己封装了成了一个组件
效果展示
组件代码
<template>
<div class="dragBtn" @touchstart="move" @click="clickMove" ref="oDiv" :style="{'width': width + 'px', 'height': height + 'px'}">
<slot>
</slot>
</div>
</template>
<script>
export default {
// distance 数组 ['上', '右', '下', '左']
props: {
distance: {
require: false,
type: Array
},
width: {
require: false,
type: Number,
default: 50
},
height: {
require: false,
type: Number,
default: 50
}
},
data () {
return {
defalutDistance: []
}
},
created () {
if (!this.distance) {
this.defalutDistance = [0, window.screen.availWidth - this.width, window.screen.availHeight - this.height,0 ]
console.log(this.defalutDistance)
}
},
methods: {
move (e) {
e.stopPropagation()
const oDiv = this.$refs['oDiv']
const disX = e.touches[0].clientX - oDiv.offsetLeft
const disY = e.touches[0].clientY - oDiv.offsetTop
document.addEventListener('touchmove', myFunction, { passive: false })
let distance = this.defalutDistance
if (this.distance) {
distance = this.distance
}
function myFunction(e) {
e.preventDefault()
let left = e.touches[0].clientX - disX
let top = e.touches[0].clientY - disY
if (left <= distance[3]) {
left = distance[3]
}
if (left >= distance[1]) {
left = distance[1]
}
if (top <= distance[0]) {
top = distance[0]
}
if (top >= distance[2]) {
top = distance[2]
}
oDiv.style.left = left + 'px'
oDiv.style.top = top + 'px'
}
document.addEventListener('touchend', () => {
document.removeEventListener('touchmove', myFunction, { passive: false })
document.removeEventListener('touchend', myFunction, { passive: false })
})
},
clickMove (e) {
e.stopPropagation()
this.$emit('clickMove', e)
}
}
}
</script>
<style scoped>
.dragBtn {
/* width: 50px;
height: 50px; */
/* border-radius: 50%; */
/* background-color: violet; */
position: fixed;
z-index: 1000;
bottom: 40px;
right: 40px;
/* background-image: url('../assets/image/change.png'); */
/* background-size: cover; */
/* border: 1px solid red; */
z-index: 99;
}
</style>
使用组件
<z-drag @clickMove="showPopup = true" :width="50" :height="50">
<van-icon name="add-o" class="addIcon" />
</z-drag>
欢迎使用!!