我正在尝试从导航组件创建导航以导航到主页(主页)的特定部分。我得到了正确的路径:http://localhost:8080/#about 但我无法让它在加载时滚动到该位置。当我手动编写路径时,它工作正常。
<template>
<div class="nav-wrapper">
<div class="nav-content">
<nav class="navigation">
<navigation-list></navigation-list>
</nav>
</div>
</div>
</template>
<script>
import navigationList from './NavigationList.vue';
export default {
components: {
navigationList
},
data() {
return {
navList: [
{
id: 'home',
title: 'Home',
link: '/'
},
{
id: 'portfolio',
title: 'Portfolio',
link: '/'
},
{
id: 'about',
title: 'About',
link: '/'
},
{
id: 'skills',
title: 'Skills',
link: '/',
},
{
id: 'contact',
title: 'Contact',
link: '/'
}
]
};
},
provide() {
return {
navList: this.navList
};
}
};
</script>
导航列表组件
<template>
<ul class="nav-list">
<navigation-element
v-for="nav in navList"
:key="nav.id"
:id="nav.id"
:title="nav.title"
:pLink="nav.link"
class="nav-list-item"
>
{{ nav.title }}
</navigation-element>
</ul>
</template>
<script>
import NavigationElement from './NavigationElement.vue';
export default {
inject: ['navList'],
components: {
NavigationElement
}
};
</script>
导航元素
<template>
<li class="nav-list-item">
<router-link :to="navigationLinks">
{{ title }}
</router-link>
</li>
</template>
<script>
export default {
props: ['id', 'title', 'pLink'],
computed: {
navigationLinks() {
return {
path: this.pLink,
hash: '#'+this.id
};
}
}
};
</script>
Router.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/home/Home.vue';
import StitchingFairy from './pages/stitchingFairy/StitchingFairy.vue';
import NewProvidance from './pages/newProvidance/NewProvidance.vue';
import Navigation from './components/nav/TheNavigation.vue';
const router = createRouter({
history: createWebHistory(),
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition;
} else {
const position = {};
if (to.hash) {
position.selector = to.hash;
if (document.querySelector(to.hash)) {
return position;
}
return false;
}
console.log(position);
}
},
routes: [
{ path: '/', component: Home },
{
name: 'stitching-fairy',
path: '/stitchingFairy',
component: StitchingFairy
},
{
name: 'new-providance',
path: '/newProvidance',
component: NewProvidance
},
{
name: 'navigation',
path: '/navigation',
component: Navigation
}
]
});
export default router;