首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vue 3 options api,如何通过ID滚动到锚

Vue 3 options api,如何通过ID滚动到锚
EN

Stack Overflow用户
提问于 2022-02-20 19:01:23
回答 1查看 570关注 0票数 0

我有Vue 3+vue路由器,用于浏览应用程序中的页面。我想导航到#从HomeView下载从不同的页面和从HomeView it self。,但它不能工作,

我的海军

代码语言:javascript
复制
          <li class="nav-item">
            <router-link :to="{ path: '/#download' }">
              <a class="nav-link me-lg-3">Download</a>
            </router-link>
          </li>

我的HomeView

代码语言:javascript
复制
  <section class="bg-gradient-primary-to-secondary" id="download"></section>

路线设置:

代码语言:javascript
复制
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import HomeView from "../views/HomeView.vue";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "home",
    component: HomeView,
  },
  {
    path: "/about",
    name: "about",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "@/views/AboutView.vue"),
  },
  {
    path: "/privacy-policy",
    name: "PrivacyPolicyView",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "@/views/PrivacyPolicyView.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  scrollBehavior(to) {
    if (to.hash) {
      return {
        selector: to.hash,
      } as any;
    }
  },
});

export default router;
EN

回答 1

Stack Overflow用户

发布于 2022-02-21 07:15:43

这段代码适用于我:

代码语言:javascript
复制
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return {
        el: to.hash,
        behavior: "smooth",
      };
    }
  },
});

Vue路由器信息

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71197754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档