在 Vue 中,当使用<a>标签创建锚点链接时,如果该链接跳转到同一个页面的不同部分(即页面内导航),Vue 会自动在 URL 中添加#和一个哈希值(如#/section1),以便在 Vue 路由中进行页面内导航。

要去掉 URL 中的#/,可以使用 Vue Router 提供的mode属性来设置路由模式。默认情况下,Vue Router 使用哈希模式(hash mode),即 URL 中会添加#和哈希值。可以将mode属性设置为history模式,这样就可以去掉 URL 中的#/

在 Vue Router 的路由配置中,添加mode: 'history'即可实现。

const router = new VueRouter({
  mode: 'history',
  routes: [
    // 路由配置
  ]
})

请注意,使用history模式需要在服务器端进行配置,以确保在刷新页面或直接访问 URL 时能正确地加载对应的页面。具体的服务器配置可能有所不同,你可以查阅相关文档或搜索适合你的服务器的配置方法。

另外,如果你只是想在同一个页面内进行锚点定位,不需要在 URL 中添加#/,你可以使用 Vue Router 的scrollBehavior属性来实现平滑滚动到锚点位置,而无需改变路由模式。

const router = new VueRouter({
  scrollBehavior(to, from, savedPosition) {
    if (to.hash) {
      return {
        selector: to.hash,
        behavior: 'smooth'
      }
    } else {
      return { x: 0, y: 0 }
    }
  },
  routes: [
    // 路由配置
  ]
})

这样,当点击具有锚点的链接时,页面将平滑滚动到对应的锚点位置,而 URL 中不会添加#/

Vue 中如何去掉 URL 后面的 #/?

原文地址: https://www.cveoy.top/t/topic/oh59 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录