当前位置:首页 > VUE

vue实现组件跟随

2026-02-10 19:56:48VUE

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>

添加跟随延迟效果

实现平滑跟随效果可添加缓动动画:

vue实现组件跟随

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/coreuseMouse 组合式 API:

import { useMouse } from '@vueuse/core'

export default {
  setup() {
    const { x, y } = useMouse()

    return { x, y }
  }
}

实现元素间相对跟随

当需要元素跟随另一个 DOM 元素时,可使用 getBoundingClientRect()

vue实现组件跟随

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)
  }
}

这些方法可以根据具体需求组合使用,实现从简单到复杂的各种跟随效果。

标签: 组件vue
分享给朋友:

相关文章

vue路由实现内部切换

vue路由实现内部切换

Vue 路由实现内部切换的方法 Vue Router 是 Vue.js 官方的路由管理器,用于实现单页应用(SPA)的页面切换。以下是几种常见的内部路由切换方式: 使用 <router-lin…

分页实现vue

分页实现vue

分页实现(Vue) 在Vue中实现分页功能通常需要结合前端分页逻辑和后端API支持。以下是两种常见的实现方式: 前端分页实现 适用于数据量较小的情况,直接在客户端完成分页逻辑。 <templ…

vue实现逻辑

vue实现逻辑

Vue 实现逻辑的核心概念 Vue.js 是一个渐进式 JavaScript 框架,其核心逻辑围绕数据驱动和组件化开发。通过响应式系统、虚拟 DOM 和组件生命周期等机制,Vue 实现了高效的前端开发…

vue实现海报

vue实现海报

Vue 实现海报生成方案 使用 html2canvas 库 html2canvas 是一个将 HTML 元素转换为 Canvas 的库,适合将 Vue 组件渲染为海报图片 安装依赖: npm in…

vue 实现excel

vue 实现excel

Vue 实现 Excel 功能 前端导出 Excel 使用 xlsx 库可以轻松实现前端 Excel 导出功能。安装依赖: npm install xlsx 导出 Excel 示例代码: impo…

vue 实现图钉

vue 实现图钉

实现图钉效果的步骤 在Vue中实现图钉(固定位置)效果,可以通过CSS的position: sticky属性或监听滚动事件动态修改元素样式。以下是两种常见方法: 方法一:使用CSS的position…