Vue 路由器滚动行为不会滚动到 id



当主页在路径'/'加载时,两个组件都能正常加载,我可以手动向下滚动到子标题部分,这样就可以了。这两个组件都有一个100vh类。当我使用"a"标签时,它会按照应该的方式转到id,但不会与路由器链接一起。

subhead是Subheadsection中div的id。

HeroHeadline 中的组件中有一个路由器链接

我在scrollBehavior函数中尝试了很多东西,但似乎都不起作用。控制台中没有错误或警告。

任何建议都将不胜感激。

路由器文件

import {
createRouter,
createWebHistory,
RouteRecordRaw,
RouterScrollBehavior,
} from "vue-router";
import HomePage from "../pages/HomePage.vue";

const routes: RouteRecordRaw[] = [
{
path: "/",
name: "Home",
component: HomePage,
},
{
path: "/:catchAll(.*)*",
component: () => import("../pages/Error404.vue"),
},
];
const scrollBehavior: RouterScrollBehavior = (to, from, savedPosition) => {
if (to.hash ) {
return { el: to.hash};
}
if (savedPosition) {

return savedPosition;
}

console.log('else');

return { left:0, top:0 };
};
const router = createRouter({
history: createWebHistory(),
scrollBehavior,
routes: routes,
});
export default router;

主页

<template>
<HeroMain />
<SubHeadSection />
</template>
<script setup lang="ts">
import HeroMain from "../components/hero/HeroMain.vue";
import SubHeadSection from '../components/sections/SubHeadSection.vue';
</script>

HeroMain

<template>
<div class="section parallax bg1">
<HeroHeadline />
</div>
</template>
<script setup lang="ts">
import HeroHeadline from './HeroHeadline.vue';</script>

HeroHeadline 中的组件中有一个路由器链接

<router-link to="#subhead">...</router-link>

堆栈

"dependencies": {
"@heroicons/vue": "^1.0.5",
"@vueuse/core": "^7.5.3",
"pinia": "^2.0.9",
"vue": "^3.2.25",
"vue-router": "^4.0.12"
},
"devDependencies": {
"@vitejs/plugin-vue": "^2.0.0",
"autoprefixer": "^10.4.2",
"postcss": "^8.4.5",
"tailwindcss": "^3.0.15",
"typescript": "^4.5.4",
"vite": "^2.7.2",
"vue-tsc": "^0.29.8"
}

我真不敢相信我花了这么多时间在这上面,但路由器链接所在组件的父容器上有一个overflow-y:scroll属性,我不确定为什么去掉它会起作用,它破坏了其他完全无关的东西,但这是另一个问题。

最新更新