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

咨询:动态调整v-navigation-drawer高度适配Footer显示状态

动态调整v-navigation-drawer高度的实现方案

核心逻辑

通过监听页面滚动事件,结合Footer元素的可见状态与高度,动态计算并设置导航抽屉的高度:

  • 滚动至页面底部时,高度设为77.5%
  • Footer完全不可见时,高度设为100%
  • Footer部分可见时,高度为100% - Footer可见高度

具体实现步骤

1. 给关键元素添加ref引用

修改模板,为导航抽屉和Footer添加ref,方便获取DOM元素信息:

<template>
  <v-app>
    <Header />
    <v-navigation-drawer 
      ref="drawer"
      width="300" 
      border="r" 
      app
    > 
      <!-- 导航内容区域 -->
    </v-navigation-drawer>
    <v-main>
      <v-container>
        <slot />
        <NavigationLink />
      </v-container>
    </v-main>
    <v-footer 
      ref="footer"
      border="t"
    >
      <v-row justify="center" no-gutters>
        <AppThemeToggle />
        <v-col class="primary lighten-2 py-4 text-center white--text" cols="12">
          <strong>Copyright {{ new Date().getFullYear() }} vuetify Corporation</strong>
        </v-col>
      </v-row>
    </v-footer>
  </v-app>
</template>

2. 编写滚动监听与高度计算逻辑

在组件脚本中实现滚动监听、高度计算与样式更新:

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const drawer = ref(null)
const footer = ref(null)
let footerTotalHeight = 0

// 计算并更新导航抽屉高度
const updateDrawerHeight = () => {
  if (!drawer.value || !footer.value) return

  // 获取页面滚动与尺寸参数
  const windowHeight = window.innerHeight
  const scrollTop = window.scrollY || document.documentElement.scrollTop
  const documentHeight = document.documentElement.scrollHeight

  // 计算Footer的可见高度
  const footerOffsetTop = footer.value.getBoundingClientRect().top
  let visibleFooterHeight = Math.max(0, windowHeight - footerOffsetTop)
  visibleFooterHeight = Math.min(visibleFooterHeight, footerTotalHeight)

  // 分场景设置抽屉高度
  let drawerHeight = '100%'
  // 滚动到页面底部时
  if (scrollTop + windowHeight >= documentHeight) {
    drawerHeight = '77.5%'
  } 
  // Footer部分可见时
  else if (visibleFooterHeight > 0) {
    drawerHeight = `calc(100% - ${visibleFooterHeight}px)`
  }

  // 应用计算后的高度
  drawer.value.style.height = drawerHeight
}

onMounted(() => {
  // 获取Footer的总高度
  footerTotalHeight = footer.value.offsetHeight
  // 初始化抽屉高度
  updateDrawerHeight()
  // 添加滚动监听
  window.addEventListener('scroll', updateDrawerHeight)
})

onUnmounted(() => {
  // 移除监听避免内存泄漏
  window.removeEventListener('scroll', updateDrawerHeight)
})
</script>

3. 移除固定样式冲突

删除之前设置的固定高度样式,避免覆盖动态计算结果:

/* 移除该固定样式 */
/* .v-navigation-drawer { height: 77.5% !important; } */

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:30:27