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

Inertia preserve scroll与scroll-region功能异常求助

解决Inertia.js侧边栏滚动位置重置及状态丢失问题

你的问题核心是滚动区域未添加唯一标识,导致Inertia无法跟踪并保存侧边栏的滚动位置。以下是具体修复步骤:

问题原因

Inertia的scroll-region属性需要配合唯一的id才能正常工作——它通过id来识别不同的滚动容器,进而保存和恢复滚动位置。你的代码中仅添加了scroll-region但未指定id,Inertia无法关联该滚动区域的状态,所以每次页面跳转都会重置滚动位置到顶部。

修复方案

  1. 给侧边栏的滚动容器添加唯一id,同时保留scroll-region属性
  2. 若需保留侧边栏的组件状态(如展开/折叠状态),需将状态存入全局状态管理(如Pinia),或确保组件在页面跳转时不被销毁(比如作为全局布局组件)

修改后的代码示例

<script setup>
import { ref } from 'vue';
import { Link } from '@inertiajs/vue3';

const links = ref([
  { name: 'Home', url: '/home' },
  { name: 'Dashboard', url: '/dashboard' },
  { name: 'Profile', url: '/profile' },
  { name: 'Settings', url: '/settings' },
  { name: 'Reports', url: '/reports' },
  { name: 'Invoices', url: '/invoices' },
  { name: 'Products', url: '/products' },
]);

defineProps({
  title: String,
});
</script>

<template>
  <div class="bg-gray-100 h-[2500px] flex">
    <!-- 添加唯一id的侧边栏滚动区域 -->
    <div class="w-64 bg-gray-800 text-white p-4 space-y-2 overflow-y-scroll h-screen" scroll-region id="sidebar-scroll-container">
      <h2 class="text-lg font-bold mb-4">Navigation</h2>
      <nav>
        <ul class="space-y-20">
          <li v-for="(link, index) in links" :key="index">
            <Link
              :href="link.url"
              class="block px-4 py-2 rounded hover:bg-gray-700"
              preserve-scroll
              preserve-state
            >
              {{ link.name }}
            </Link>
          </li>
        </ul>
      </nav>
    </div>

    <!-- Main Content -->
    <main class="flex flex-col p-4 flex-1 h-full">
      <slot />
    </main>
  </div>
</template>

额外说明

  • preserve-scroll作用于页面整体滚动,而scroll-region+id才是针对局部滚动容器的状态保存
  • 如果侧边栏有自定义状态(比如展开菜单),仅靠Inertia的preserve-state可能不够——因为组件若在页面跳转时被重新渲染,内部状态会丢失,此时建议将状态存入全局状态管理库(如Pinia),或把侧边栏作为全局布局的一部分,确保组件实例不被销毁

内容的提问来源于stack exchange,提问作者Aleksandar Đokić

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 06:02:43