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

我给你最完整、最标准、可直接复制运行 的 Vue3 路由全套示例,包含: ✅ 路由配置

✅ 页面跳转

✅ 路由传参

✅ 动态路由

✅ 嵌套路由(子路由)

✅ 404 页面

✅ 路由守卫(登录拦截)

✅ 组合式 API 完整用法

一、项目结构(照着建)

bash 复制代码
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

二、安装路由

bash 复制代码
npm install vue-router@4

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

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

javascript 复制代码
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

javascript 复制代码
import { createApp } from 'vue'
import App from './App.vue'
import router from './router' // 导入路由

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

3. 根组件:App.vue

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(首页)

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(关于页)

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(动态路由)

vue 复制代码
<template>
  <h2>用户页</h2>
  <p>用户 ID:{{ route.params.id }}</p>
</template>

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

🔐 Login.vue(登录页)

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(嵌套父路由)

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(子页面)

vue 复制代码
<!-- Profile.vue -->
<template><h4>个人资料</h4></template>

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

❌ NotFound.vue

vue 复制代码
<template>
  <h2>404 页面不存在</h2>
</template>

五、运行项目

bash 复制代码
npm run dev

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

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

总结

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

相关推荐
IT_陈寒10 小时前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
子兮曰11 小时前
Agency-Agents 深度解析:400+ AI 专家的"梦之队"如何重塑开发工作流
前端·后端·vibecoding
竹林81812 小时前
用 The Graph 查询链上数据实战:从手搓 RPC 到 Subgraph,我的 NFT 项目数据加载快了 10 倍
前端·javascript
妙码生花12 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go
Awu122713 小时前
⚡从零开发 Agent CLI(五)实现一个可治理、可扩展的工具系统
前端·人工智能·claude
咪库咪库咪13 小时前
Vue3-生命周期
前端
莪_幻尘13 小时前
你的 AI Skill 越多越蠢?Token 上下文爆炸的求生指南
前端·ai编程
lichenyang45314 小时前
从 has.echo 到异步 API 注册表:一次 ASCF API 回调不触发的排查复盘
前端
林瞅瞅14 小时前
Nuxt3 项目部署 Nginx 防盗链后特定 JS 文件 403 问题修复方案
前端
kyriewen14 小时前
别再每次都 Google 了:我整理了前端日常最常踩的 10 个 Git 坑,附速查表
前端·javascript·git