Vue3 + Vue Router 4 完整示例(可直接运行)

28 阅读2分钟

我给你最完整、最标准、可直接复制运行的 Vue3 路由全套示例,包含: ✅ 路由配置
✅ 页面跳转
✅ 路由传参
✅ 动态路由
✅ 嵌套路由(子路由)
✅ 404 页面
✅ 路由守卫(登录拦截)
✅ 组合式 API 完整用法

一、项目结构(照着建)

src/
├── router/
│   └── index.js       # 路由配置
├── views/             # 页面组件
│   ├── Home.vue
│   ├── About.vue
│   ├── User.vue
│   ├── Login.vue
│   ├── NotFound.vue
│   └── Dashboard/     # 嵌套路由文件夹
│       ├── Dashboard.vue
│       ├── Profile.vue
│       └── Order.vue
├── App.vue
└── main.js

二、安装路由

npm install vue-router@4

三、完整代码(直接复制)

1. 路由配置:src/router/index.js

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

// 导入页面
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import NotFound from '../views/NotFound.vue'

// 路由规则
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true } // 需要登录才能访问
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue') // 懒加载
  },
  {
    path: '/user/:id', // 动态路由
    name: 'User',
    component: () => import('../views/User.vue')
  },
  {
    path: '/login',
    component: Login
  },
  // 嵌套路由示例
  {
    path: '/dashboard',
    component: () => import('../views/Dashboard/Dashboard.vue'),
    meta: { requiresAuth: true },
    children: [
      { path: 'profile', component: () => import('../views/Dashboard/Profile.vue') },
      { path: 'order', component: () => import('../views/Dashboard/Order.vue') }
    ]
  },
  // 404 页面
  {
    path: '/:pathMatch(.*)*',
    component: NotFound
  }
]

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

// 路由守卫(登录验证)
router.beforeEach((to, from, next) => {
  const isLogin = localStorage.getItem('token') // 模拟登录状态

  if (to.meta.requiresAuth && !isLogin) {
    next('/login') // 未登录,跳转到登录页
  } else {
    next() // 放行
  }
})

export default router

2. 挂载路由:src/main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router' // 导入路由

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

3. 根组件:App.vue

<template>
  <nav>
    <router-link to="/">首页</router-link> |
    <router-link to="/about">关于</router-link> |
    <router-link to="/user/1001">用户 1001</router-link> |
    <router-link to="/dashboard">控制台</router-link> |
    <router-link to="/login">登录</router-link>
  </nav>

  <div style="padding: 20px;">
    <router-view></router-view> <!-- 页面出口 -->
  </div>
</template>

四、页面组件代码

🏠 Home.vue(首页)

<template>
  <h2>首页(需要登录)</h2>
  <button @click="goToAbout">跳转到关于页</button>
</template>

<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()

const goToAbout = () => {
  router.push('/about')
}
</script>

ℹ️ About.vue(关于页)

<template>
  <h2>关于页</h2>
  <p>当前路径:{{ route.path }}</p>
  <button @click="back">返回</button>
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()

const back = () => {
  router.go(-1)
}
</script>

👤 User.vue(动态路由)

<template>
  <h2>用户页</h2>
  <p>用户 ID:{{ route.params.id }}</p>
</template>

<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
</script>

🔐 Login.vue(登录页)

<template>
  <h2>登录页</h2>
  <button @click="login">登录</button>
</template>

<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()

const login = () => {
  localStorage.setItem('token', '123456') // 模拟登录
  router.push('/') // 跳回首页
}
</script>

📊 Dashboard.vue(嵌套父路由)

<template>
  <h2>控制台</h2>
  <router-link to="/dashboard/profile">个人资料</router-link> |
  <router-link to="/dashboard/order">订单</router-link>
  <router-view></router-view>
</template>

📄 Profile.vue + Order.vue(子页面)

<!-- Profile.vue -->
<template><h4>个人资料</h4></template>

<!-- Order.vue -->
<template><h4>订单页面</h4></template>

❌ NotFound.vue

<template>
  <h2>404 页面不存在</h2>
</template>

五、运行项目

npm run dev

六、这个示例包含的所有功能

  1. 基础路由/ /about
  2. 动态路由/user/1001
  3. 嵌套路由/dashboard/profile
  4. 路由懒加载:优化性能
  5. 路由守卫:登录权限控制
  6. 404 页面
  7. 组合式 APIuseRouter useRoute
  8. 声明式导航 + 编程式导航

总结

这是企业级标准 Vue3 路由完整示例直接复制即可运行,包含你开发项目会用到的 99% 路由功能。