Vue Router基础 #

一、Vue Router简介 #

Vue Router是Vue.js官方路由管理器,用于构建单页应用(SPA)。

1.1 安装 #

bash
npm install vue-router@4

1.2 基本配置 #

javascript
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'

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

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

export default router
javascript
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.use(router)
app.mount('#app')

1.3 路由出口 #

vue
<template>
  <nav>
    <router-link to="/">首页</router-link>
    <router-link to="/about">关于</router-link>
  </nav>
  
  <router-view />
</template>

二、路由配置 #

2.1 路由模式 #

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

// HTML5 History模式(推荐)
const router = createRouter({
  history: createWebHistory(),
  routes
})

// Hash模式
const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// Memory模式(非浏览器环境)
import { createMemoryHistory } from 'vue-router'
const router = createRouter({
  history: createMemoryHistory(),
  routes
})

2.2 路由定义 #

javascript
const routes = [
  // 基本路由
  {
    path: '/',
    component: Home
  },
  
  // 命名路由
  {
    path: '/user',
    name: 'User',
    component: User
  },
  
  // 多个命名视图
  {
    path: '/layout',
    components: {
      default: Main,
      sidebar: Sidebar,
      header: Header
    }
  },
  
  // 重定向
  {
    path: '/home',
    redirect: '/'
  },
  
  // 别名
  {
    path: '/users',
    component: User,
    alias: '/people'
  }
]

2.3 嵌套路由 #

javascript
const routes = [
  {
    path: '/user',
    component: User,
    children: [
      {
        path: '',           // /user
        component: UserHome
      },
      {
        path: 'profile',    // /user/profile
        component: UserProfile
      },
      {
        path: 'posts',      // /user/posts
        component: UserPosts
      }
    ]
  }
]
vue
<!-- User.vue -->
<template>
  <div>
    <h2>用户中心</h2>
    <nav>
      <router-link to="/user">首页</router-link>
      <router-link to="/user/profile">资料</router-link>
      <router-link to="/user/posts">文章</router-link>
    </nav>
    <router-view />
  </div>
</template>

三、动态路由 #

3.1 路由参数 #

javascript
const routes = [
  {
    path: '/user/:id',
    component: User
  },
  
  // 多个参数
  {
    path: '/user/:id/post/:postId',
    component: UserPost
  },
  
  // 可选参数
  {
    path: '/user/:id?',
    component: User
  },
  
  // 可重复参数
  {
    path: '/files/:path*',     // 匹配 /files/a/b/c
    component: Files
  },
  {
    path: '/files/:path+',     // 至少匹配一个
    component: Files
  },
  
  // 正则匹配
  {
    path: '/user/:id(\\d+)',   // 只匹配数字
    component: User
  }
]

3.2 获取路由参数 #

vue
<template>
  <div>
    <p>用户ID: {{ $route.params.id }}</p>
    <p>查询参数: {{ $route.query }}</p>
  </div>
</template>

<script setup>
import { useRoute } from 'vue-router'
import { watch } from 'vue'

const route = useRoute()

// 访问参数
console.log(route.params.id)
console.log(route.query.keyword)

// 监听参数变化
watch(
  () => route.params.id,
  (newId) => {
    fetchUser(newId)
  }
)
</script>

3.3 捕获所有路由 #

javascript
const routes = [
  // 捕获所有路由
  {
    path: '/:pathMatch(.*)*',
    component: NotFound
  },
  
  // 捕获特定前缀的所有路由
  {
    path: '/admin/:pathMatch(.*)*',
    component: AdminNotFound
  }
]

四、编程式导航 #

4.1 基本导航 #

vue
<script setup>
import { useRouter } from 'vue-router'

const router = useRouter()

// 导航到不同路由
function goHome() {
  router.push('/')
}

// 命名路由
function goToUser() {
  router.push({ name: 'User', params: { id: 1 } })
}

// 带查询参数
function search() {
  router.push({ path: '/search', query: { keyword: 'vue' } })
}

// 替换当前路由(不留历史记录)
function replaceRoute() {
  router.replace('/about')
}

// 前进/后退
function goBack() {
  router.go(-1)
}

function goForward() {
  router.go(1)
}
</script>
vue
<template>
  <!-- 基本用法 -->
  <router-link to="/">首页</router-link>
  
  <!-- 绑定to -->
  <router-link :to="'/user/' + userId">用户</router-link>
  
  <!-- 命名路由 -->
  <router-link :to="{ name: 'User', params: { id: 1 } }">
    用户
  </router-link>
  
  <!-- 带查询参数 -->
  <router-link :to="{ path: '/search', query: { keyword: 'vue' } }">
    搜索
  </router-link>
  
  <!-- 替换模式 -->
  <router-link to="/about" replace>关于</router-link>
  
  <!-- 自定义标签 -->
  <router-link to="/about" custom v-slot="{ navigate }">
    <button @click="navigate">关于</button>
  </router-link>
  
  <!-- 激活状态 -->
  <router-link to="/about" active-class="active">
    关于
  </router-link>
  
  <!-- 精确匹配 -->
  <router-link to="/" exact-active-class="exact-active">
    首页
  </router-link>
</template>

五、命名视图 #

5.1 配置命名视图 #

javascript
const routes = [
  {
    path: '/layout',
    components: {
      default: Main,
      sidebar: Sidebar,
      header: Header
    }
  }
]

5.2 使用命名视图 #

vue
<template>
  <div class="layout">
    <router-view name="header" />
    <div class="main">
      <router-view name="sidebar" />
      <router-view />  <!-- default视图 -->
    </div>
  </div>
</template>

六、路由懒加载 #

6.1 动态导入 #

javascript
const routes = [
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
  },
  {
    path: '/user',
    name: 'User',
    component: () => import('../views/User.vue')
  }
]

6.2 分组打包 #

javascript
const routes = [
  {
    path: '/admin',
    component: () => import(/* webpackChunkName: "admin" */ '../views/Admin.vue'),
    children: [
      {
        path: 'users',
        component: () => import(/* webpackChunkName: "admin" */ '../views/AdminUsers.vue')
      },
      {
        path: 'settings',
        component: () => import(/* webpackChunkName: "admin" */ '../views/AdminSettings.vue')
      }
    ]
  }
]

七、路由元信息 #

7.1 定义元信息 #

javascript
const routes = [
  {
    path: '/admin',
    component: Admin,
    meta: {
      requiresAuth: true,
      title: '管理后台'
    }
  },
  {
    path: '/user/:id',
    component: User,
    meta: {
      requiresAuth: true,
      title: '用户详情'
    }
  }
]

7.2 使用元信息 #

vue
<script setup>
import { useRoute } from 'vue-router'
import { watch } from 'vue'

const route = useRoute()

// 访问元信息
console.log(route.meta.title)

// 监听路由变化更新标题
watch(
  () => route.meta.title,
  (title) => {
    document.title = title || '默认标题'
  },
  { immediate: true }
)
</script>

八、滚动行为 #

javascript
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 返回顶部
    return { top: 0 }
    
    // 保持滚动位置(浏览器前进/后退)
    if (savedPosition) {
      return savedPosition
    }
    
    // 滚动到锚点
    if (to.hash) {
      return {
        el: to.hash,
        behavior: 'smooth'
      }
    }
    
    // 滚动到指定位置
    return { top: 0, left: 0, behavior: 'smooth' }
  }
})

九、完整示例 #

javascript
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: { title: '首页' }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/user',
    name: 'UserLayout',
    component: () => import('../layouts/UserLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'UserHome',
        component: () => import('../views/user/Home.vue')
      },
      {
        path: 'profile',
        name: 'UserProfile',
        component: () => import('../views/user/Profile.vue'),
        meta: { title: '个人资料' }
      },
      {
        path: 'posts',
        name: 'UserPosts',
        component: () => import('../views/user/Posts.vue'),
        meta: { title: '我的文章' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'),
    meta: { title: '页面未找到' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    }
    if (to.hash) {
      return { el: to.hash, behavior: 'smooth' }
    }
    return { top: 0 }
  }
})

export default router

十、总结 #

功能 API
创建路由 createRouter()
路由模式 createWebHistory() / createWebHashHistory()
导航 router.push() / router.replace() / router.go()
路由信息 useRoute()
路由实例 useRouter()
路由出口 <router-view>
路由链接 <router-link>
路由参数 route.params / route.query

Vue Router要点:

  • 使用createRouter创建路由实例
  • router-view作为路由出口
  • router-link创建导航链接
  • 动态路由使用:param语法
  • 编程式导航使用router.push
  • 路由懒加载优化性能
最后更新:2026-03-26