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

如何在Vuetify v-slide-group中编程识别完全与部分显示的slide

实现方案

方案1:基于 Intersection Observer 实现(推荐,性能更优)

利用浏览器内置的交叉观察器API,自动监听元素在容器内的可见比例,无需频繁监听滚动事件计算位置。
完整代码如下:

模板部分

<template>
  <v-slide-group ref="slideGroup">
    <v-slide-item 
      v-for="(slide, i) in slides" 
      :key="i"
      :ref="el => { if (el) slideRefs[i] = el.$el }"
      :class="{
        'fully-visible': visibleStatus[i] === 'full',
        'partial-visible': visibleStatus[i] === 'partial'
      }"
    >
      <v-card width="500" height="200" color="yellow">
          slide {{i}}
      </v-card>
    </v-slide-item>
  </v-slide-group>
</template>

逻辑部分

<script>
export default {
  data() {
    return {
      slides: [1, 2, 3, 4, 5],
      slideRefs: [],
      visibleStatus: [],
      observer: null
    };
  },
  mounted() {
    // 初始化交叉观察器,监听元素在slide group容器内的可见比例
    this.observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        const index = this.slideRefs.indexOf(entry.target)
        if (index === -1) return
        // 可见比例为1代表完全展示,小于1代表部分展示
        this.visibleStatus[index] = entry.intersectionRatio === 1 ? 'full' : 'partial'
      })
    }, {
      // 指定滑动容器为观察根节点
      root: this.$refs.slideGroup.$el.querySelector('.v-slide-group__content'),
      threshold: [0, 1]
    })
    // 等待DOM渲染完成后开始监听所有slide元素
    this.$nextTick(() => {
      this.slideRefs.forEach(ref => this.observer.observe(ref))
    })
  },
  beforeDestroy() {
    // 销毁观察器避免内存泄漏
    this.observer?.disconnect()
  }
}
</script>

样式部分

<style scoped>
/* 完全展示的slide样式 */
.fully-visible .v-card {
  border: 3px solid #4caf50;
}
/* 部分展示的slide样式 */
.partial-visible .v-card {
  border: 3px solid #f44336;
}
</style>

方案2:基于滚动事件手动计算(兼容性更好)

如果需要兼容不支持Intersection Observer的老旧环境,可以通过监听滑动事件,手动计算每个slide和容器的位置关系判断可见状态:
给v-slide-group绑定@scroll="handleScroll",事件逻辑如下:

methods: {
  handleScroll() {
    const container = this.$refs.slideGroup.$el.querySelector('.v-slide-group__content')
    const containerRect = container.getBoundingClientRect()
    this.slideRefs.forEach((slide, index) => {
      const slideRect = slide.getBoundingClientRect()
      const isFullyVisible = 
        slideRect.left >= containerRect.left && 
        slideRect.right <= containerRect.right
      this.visibleStatus[index] = isFullyVisible ? 'full' : 'partial'
    })
  }
}

组件挂载后也需要主动调用一次handleScroll初始化初始状态的样式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:18:03