跳转至

第二章:路由配置

路由定义

基本路由

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
  { path: '/contact', component: Contact }
]

命名路由

const routes = [
  {
    path: '/user/:id',
    name: 'User',
    component: User
  }
]

// 使用
<router-link :to="{ name: 'User', params: { id: 1 } }">用户</router-link>

重定向

const routes = [
  { path: '/', redirect: '/home' },
  { path: '/home', component: Home }
]

别名

const routes = [
  {
    path: '/home',
    component: Home,
    alias: '/index'
  }
]

路由模式

History 模式

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes
})

Hash 模式

import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

路由组件

命名视图

const routes = [
  {
    path: '/',
    components: {
      default: Home,
      header: Header,
      footer: Footer
    }
  }
]
<template>
  <router-view name="header" />
  <router-view />
  <router-view name="footer" />
</template>

小结

路由配置要点:

  • 基本路由:path、component
  • 命名路由:name 属性
  • 重定向:redirect
  • 别名:alias
  • 路由模式:History、Hash

下一章我们将学习路由导航。