拖拽
适用于一些点击后拖拽的场景
npm i @vueuse/core
<div ref="target">
<img ref="boxRef">
</div>
import {computed, onMounted, reactive, ref} from 'vue'
import {useMouseInElement} from '@vueuse/core'
const target = ref(null) // 父元素的引用
const boxRef = ref(null) // 拖拽的目标元素的引用
const canDrag = ref(false) // 目标元素是否能被拖拽
const mousePosition = reactive({
left: 0,
top: 0
})
// 拖拽元素的位置
const position = reactive({
left: '0px',
top: '0px'
})
// 使用@vueuse/core获取目标元素在父元素中的位置
const {elementX, elementY, isOutside} = useMouseInElement(target)
onMounted(() => {
if (boxRef.value) {
// 获取鼠标在拖拽元素内的坐标
boxRef.value.onmousedown = (e) => {
mousePosition.left = e.clientX - target.value.offsetLeft - boxRef.value.offsetLeft
mousePosition.top = e.clientY - target.value.offsetTop - boxRef.value.offsetTop
boxRef.value.onmousemove = () => {
canDrag.value = true
}
}
document.documentElement.onmouseup = () => {
boxRef.value && (boxRef.value.onmousemove = null);
canDrag.value = false
}
}
})
watch([elementX, elementY, isOutside], () => {
if (!canDrag.value) return
// 鼠标在图片的区域之外,不需要计算坐标
if (isOutside.value) return
position.left = elementX.value - mousePosition.left
position.top = elementY.value - mousePosition.top
position.left += 'px'
position.top += 'px'
})