VueRouter默认路由详解

发布时间:2023-05-20

一、VueRouter默认路由显示不出东西

当我们在Vue项目中使用VueRouter时,会发现直接访问首页的时候并没有任何东西显示出来,这是因为默认情况下,VueRouter需要依赖于两个配置文件:

  • router/index.js 用于配置VueRouter路由
  • App.vue 用于引入VueRouter路由配置 在这两个文件都被正确配置以后,我们才能看到页面上正常的内容显示。

二、Vue默认路由

当我们创建一个新的Vue项目的时候,默认情况下,Vue会自动为我们创建一个路由文件并进行配置。这个路由配置文件主要包括:

  • / 路径对应的组件:src/views/Home.vue
  • /about 路径对应的组件:src/views/About.vue

三、VueRouter路由的作用

VueRouter的主要作用是在Vue项目中实现客户端路由的跳转以及管理。它能够监听浏览器URL地址的变化,并将变化反映到Vue组件中,从而实现局部刷新的效果。

四、VueRouter的路由模式

VueRouter有两种路由模式:hashhistory。默认情况下,VueRouter的路由模式是 hash 模式,它将路由信息保存在URL地址的 # 后面。 如果我们想要改变VueRouter的路由模式,可以在 router/index.js 文件中进行如下配置:

import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})
export default router

以上配置表示将VueRouter的路由模式改为 history 模式。

五、VueRouter动态添加路由

除了在 router/index.js 中静态配置路由信息以外,我们还可以在Vue组件中动态添加路由。 在Vue组件中动态添加路由的代码如下:

import { useRouter } from 'vue-router'
const router = useRouter()
function addRoute() {
  router.addRoute({
    path: '/dynamic-route',
    component: DynamicRoute
  })
}

以上代码表示在 /dynamic-route 路径下动态添加一个组件 DynamicRoute 作为路由。

六、路由器默认mercury

除了VueRouter默认的 hash 模式和 history 模式以外,还有一个名为 mercury 的路由模式。 我们可以在 router/index.js 中进行如下配置,即可将VueRouter的路由模式改为 mercury 模式:

import { createRouter, createMemoryHistory } from 'vue-router'
const router = createRouter({
  history: createMemoryHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})
export default router

七、VueRouter路由跳转

VueRouter提供了两种方式进行路由跳转:

  • <router-link> 标签在 <template> 中,用于生成可点击的链接
  • router.push 方法在JS代码中,用于编程式地进行路由跳转 路由跳转的代码示例:
<!-- 路由链接 -->
<router-link to="/">首页</router-link>
<!-- JS代码中的路由跳转 -->
function navigateToAboutPage() {
  router.push('/about')
}

八、VueRouter嵌套路由

VueRouter支持嵌套路由,也就是说一个路由下面还可以有它的子路由。 在 router/index.js 中进行嵌套路由配置示例:

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    {
      path: '/about',
      component: About,
      children: [
        { path: '', component: AboutHome },
        { path: 'contact', component: AboutContact },
        { path: 'team', component: AboutTeam }
      ]
    }
  ]
})
export default router

以上代码表示在 /about 路由下面嵌套了三个子路由,分别是 /about/about/contact/about/team

九、VueRouter清空路由

我们可以使用 router.replace 方法来清空路由,代码示例如下:

const clearRoute = () => {
  router.replace('/')
}

以上代码表示将路由清空,回到 / 路径。

十、VueRouter路由模式区别选取

在选择VueRouter的路由模式时,需要根据具体的需求来进行选择。

  • hash 模式适合单页应用,因为在单页应用中,所有页面切换都是在同一个页面内完成的,使用 hash 模式可以避免在服务器端进行URL地址的配置。
  • history 模式适合支持服务器端渲染的多页应用,因为 history 模式需要在服务器端进行URL地址的配置。
  • mercury 模式主要是为了提高性能而创建的,它采用HTML5 PushState来实现路由跳转,相比于 hash 模式和 history 模式,可以提供更好的性能和更好的用户体验。