vue实现组件跟随
Vue 实现组件跟随效果
在 Vue 中实现组件跟随效果通常需要监听鼠标或触摸事件,并动态更新组件位置。以下是几种常见实现方式:
使用鼠标事件实现基础跟随
通过监听 mousemove 事件获取光标坐标,将坐标赋值给组件样式:
<template>
<div class="follower" :style="{ left: x + 'px', top: y + 'px' }">
跟随元素
</div>
</template>
<script>
export default {
data() {
return {
x: 0,
y: 0
}
},
mounted() {
window.addEventListener('mousemove', this.updatePosition)
},
beforeDestroy() {
window.removeEventListener('mousemove', this.updatePosition)
},
methods: {
updatePosition(e) {
this.x = e.clientX
this.y = e.clientY
}
}
}
</script>
<style>
.follower {
position: fixed;
pointer-events: none;
transform: translate(-50%, -50%);
}
</style>
添加跟随延迟效果
实现平滑跟随效果可添加缓动动画:
methods: {
updatePosition(e) {
const targetX = e.clientX
const targetY = e.clientY
const easing = 0.1
this.x += (targetX - this.x) * easing
this.y += (targetY - this.y) * easing
}
}
通过 VueUse 使用更简洁的实现
利用 @vueuse/core 的 useMouse 组合式 API:
import { useMouse } from '@vueuse/core'
export default {
setup() {
const { x, y } = useMouse()
return { x, y }
}
}
实现元素间相对跟随
当需要元素跟随另一个 DOM 元素时,可使用 getBoundingClientRect():
methods: {
followElement() {
const target = this.$refs.targetElement
const rect = target.getBoundingClientRect()
this.x = rect.left + rect.width/2
this.y = rect.top + rect.height/2
}
}
移动端触摸支持
添加触摸事件支持:
mounted() {
window.addEventListener('mousemove', this.updatePosition)
window.addEventListener('touchmove', this.handleTouch)
},
methods: {
handleTouch(e) {
const touch = e.touches[0]
this.updatePosition({
clientX: touch.clientX,
clientY: touch.clientY
})
}
}
性能优化建议
对于复杂场景,建议使用 requestAnimationFrame 进行优化:

methods: {
startFollowing() {
const follow = () => {
this.updatePosition()
this.rafId = requestAnimationFrame(follow)
}
this.rafId = requestAnimationFrame(follow)
},
stopFollowing() {
cancelAnimationFrame(this.rafId)
}
}
这些方法可以根据具体需求组合使用,实现从简单到复杂的各种跟随效果。






