You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中跨组件实现Scroll to a specific Element的方法

Vue中跨组件实现滚动到指定元素的方法

针对触发点击的元素(Bio组件内)与目标滚动元素(Services组件所在区域)分属不同组件的场景,以下是几种实用实现方案:

方案一:自定义事件 + 原生scrollIntoView(Vue2/Vue3通用)

这是最常用的跨组件通信触发滚动的方式,通过父组件作为中间层传递事件:

步骤1:修改父组件模板,给目标区域添加ref

给Services组件所在的section设置唯一ref,方便后续获取DOM元素:

<template>
  <div class="container">
    <div class="section">
      <Bio @scroll-to-services="handleScrollToServices" />
    </div>
    <!-- ...其他组件 -->
    <div class="section" ref="servicesSection"> 
      <Services />
    </div>
    <!-- ...其他组件 -->
  </div>
</template>

步骤2:父组件实现滚动方法

在父组件的脚本中编写触发滚动的逻辑,调用原生scrollIntoView实现平滑滚动:

Vue2 版本

<script>
export default {
  methods: {
    handleScrollToServices() {
      this.$refs.servicesSection?.scrollIntoView({
        behavior: 'smooth', // 平滑滚动
        block: 'start' // 滚动到元素顶部对齐
      })
    }
  }
}
</script>

Vue3 版本(组合式API)

<script setup>
import { ref } from 'vue'
const servicesSection = ref(null)

const handleScrollToServices = () => {
  servicesSection.value?.scrollIntoView({
    behavior: 'smooth',
    block: 'start'
  })
}
</script>

步骤3:Bio组件触发滚动事件

在Bio组件内的点击元素上绑定事件,通过$emit(Vue2)或emit(Vue3)向父组件发送滚动指令:

Vue2 版本

<template>
  <div>
    <!-- 点击该文本触发滚动 -->
    <span @click="$emit('scroll-to-services')">滚动到服务板块</span>
  </div>
</template>

Vue3 版本(组合式API)

<template>
  <div>
    <span @click="emit('scroll-to-services')">滚动到服务板块</span>
  </div>
</template>

<script setup>
import { defineEmits } from 'vue'
const emit = defineEmits(['scroll-to-services'])
</script>

方案二:Vue3 专属——Provide/Inject 直接传递滚动方法

如果是Vue3项目,可以跳过父组件中转,直接通过provide和inject将滚动方法传递给Bio组件:

父组件提供滚动方法

<script setup>
import { ref, provide } from 'vue'
const servicesSection = ref(null)

const scrollToServices = () => {
  servicesSection.value?.scrollIntoView({ behavior: 'smooth' })
}
// 提供方法给子组件
provide('scrollToServices', scrollToServices)
</script>

Bio组件注入并调用方法

<template>
  <span @click="scrollToServices">滚动到服务板块</span>
</template>

<script setup>
import { inject } from 'vue'
const scrollToServices = inject('scrollToServices')
</script>

方案三:原生锚点(极简方案)

如果不需要自定义滚动逻辑,直接给目标区域加id,在Bio组件内用锚点链接即可:

父组件给目标区域加id

<div class="section" id="services-section"> 
  <Services />
</div>

Bio组件内添加锚点(单页应用需注意路由模式)

<template>
  <!-- 阻止默认跳转避免路由变化,直接触发滚动 -->
  <a href="#services-section" @click.prevent>滚动到服务板块</a>
</template>

内容的提问来源于stack exchange,提问作者Jakub Vorel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 19:41:00