当前位置:首页 > 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>

添加跟随延迟效果

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

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

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 进行优化:

vue实现组件跟随

methods: {
  startFollowing() {
    const follow = () => {
      this.updatePosition()
      this.rafId = requestAnimationFrame(follow)
    }
    this.rafId = requestAnimationFrame(follow)
  },
  stopFollowing() {
    cancelAnimationFrame(this.rafId)
  }
}

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

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

相关文章

vue 实现视频

vue 实现视频

Vue 实现视频播放功能 使用 Vue 实现视频播放功能可以通过 HTML5 的 <video> 标签或第三方库(如 video.js)来实现。以下是两种常见的方法: 使用 HTML5…

vue 实现href

vue 实现href

Vue 实现 href 的方法 在 Vue 中实现 href 功能可以通过多种方式,具体取决于需求场景。以下是几种常见的方法: 使用 <a> 标签 直接使用 HTML 的 <a&g…

实现vue datepicker

实现vue datepicker

安装依赖 使用 vue-datepicker 或第三方库如 v-calendar 或 vue2-datepicker。以 vue2-datepicker 为例: npm install vue2…

javascript实现vue

javascript实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,主要包括数据绑定、响应式系统和虚拟 DOM。以下是一个简化的实现示例。 数据响应式系统 通过 Object.de…

vue 动画实现

vue 动画实现

Vue 动画实现方式 Vue 提供了多种方式实现动画效果,主要分为内置组件和第三方库集成。 使用 Vue 内置过渡组件 Vue 的 <transition> 和 <transiti…

vue 实现搜索

vue 实现搜索

实现 Vue 搜索功能 在 Vue 中实现搜索功能通常涉及以下几个关键步骤: 数据绑定与输入监听 使用 v-model 双向绑定搜索输入框的值,监听用户输入: <template>…