使用 Vue Router 滚动到锚点

我需要在 vuejs 中设置一个锚链接才能转到:

<h1 id="apply">Test anchor</h1>

以下内容有效,但它将 url 更改为 http://localhost:8080/#/apply

<a href="#apply" class="btn btn-primary mt-3">Apply Now</a>

如果我刷新页面,它不知道该去哪里。

以下内容也不适合我。它甚至不会下降到#apply。

<router-link to="/careers/job-1#apply">test</router-link>

如何使用 vuejs 路由设置锚链接?


茅侃侃
浏览 180回答 2
2回答

蝴蝶不菲

将 apath和 ahash属性添加到您的to对象中:<router-link :to="{ path: '/careers/job-1', hash: '#apply' }">test</router-link>并添加scrollBehavior到您的路由器定义中:const router = new VueRouter({&nbsp; ...&nbsp; scrollBehavior (to, from, savedPosition) {&nbsp; &nbsp; if (to.hash) {&nbsp; &nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; selector: to.hash,&nbsp; &nbsp; &nbsp; &nbsp; behavior: 'smooth'&nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; }&nbsp; &nbsp; return { x: 0, y: 0 };&nbsp; // Go to the top of the page if no hash&nbsp; },&nbsp; ...})现在它应该滚动(平滑,除非您删除该behavior属性)到由哈希定义的锚点

SMILET

因此,如果其他人在提出问题几年后偶然发现这个问题,我会找到另一种方法来实现所需的行为:在我的项目中,我喜欢通过传递给 vue-router-4 的 createRouter() 方法的配置数组在导航栏上显示路由作为示例:关键只是要了解 vue-router 内部如何工作,以及它们在 RouteRecordRaw 类上有一个名为“redirect”的属性,它是一个 RouteRecordRedirectOption-Type。在那里我们可以定义它应该导航到的哈希:const routes: Array<RouteRecordRaw> = [&nbsp; &nbsp; { name: 'home', path: '/', meta: { name: 'Home' }, component: () => import("@/pages/HomePage.vue") },&nbsp; &nbsp; { name: 'members', path: '/', meta: { name: 'Members'} , redirect: { name: 'home', hash: '#members' }},&nbsp; &nbsp; { name: 'events', path: '/', meta: { name: 'Events'} , redirect: { name: 'home', hash: '#events' }}];如果我们随后将此数组传递给 createRouter 方法,我们可以通过其 getRoutes() 方法访问导航栏 vue 文件中的路由列表:// router.tsconst router = createRouter({&nbsp; &nbsp; history: createWebHistory(),&nbsp; &nbsp; routes: routes,&nbsp; &nbsp; scrollBehavior(to) {&nbsp; &nbsp; &nbsp; &nbsp; if (to.hash) return { el: to.hash, behavior: 'smooth' };&nbsp; &nbsp; &nbsp; &nbsp; return { top: 0, behavior: 'smooth' };&nbsp; &nbsp; }});// TheNavbar.vueconst routes = router.getRoutes();然后可以在 router-link 标记中访问该变量,如下所示:<router-link v-for="route in routes" :key="route.name" :to="route" class="nav-element">{{ route.meta.name }}</router-link>为了澄清上述情况,我很少使用 RouteRecordRaw 类的属性名称将其显示在我的导航栏中,因为它应该是小写的。这是路由的名称,而不是我们应该在前端显示的内容(除了在网址栏中)。因此另一种方法是将所有杂项信息放入元属性中。我希望上述解决方案能够到达合适的人手中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript