Vue基础教程(163)使用Vue Router开发单页面应用:【保姆级教程】Vue Router:让你的单页面应用“浪”到飞起!

Vue Router入门与实战

一、为什么你的网页需要“瞬移大法”?

想象一下:每次点击链接都要经历“白屏→加载→刷新”的死亡三连,用户不跑路才怪!而单页面应用(SPA)就像一家宝藏店铺——所有货品(页面内容)早已备齐,顾客(用户)只需抬抬手指,展示区瞬间切换,爽到飞起!

Vue Router正是实现这种魔法的隐形传送门。它能让你的Vue应用在不刷新页面的情况下,通过URL变化精准展示不同组件。举个栗子🌰:

  • 传统网站:点击「关于我们」→ 页面全刷新 → 等待3秒 → 显示新内容
  • SPA应用:点击「关于我们」→ 0.1秒内无感切换 → 内容丝滑呈现

二、手把手搭建你的第一个传送门

1. 前期准备:先整个Vue项目
# 用Vue CLI快速创建项目(确保已安装node.js)
npm create vue@latest my-spa-app
cd my-spa-app
npm install
2. 安装魔法道具:Vue Router
npm install vue-router@4
3. 核心配置:路由地图绘制

/src/router/index.js中(需要手动创建router目录):

import { createRouter, createWebHistory } from 'vue-router'
import HomePage from '../components/HomePage.vue'
import AboutPage from '../components/AboutPage.vue'

// 定义路由规则:什么路径显示哪个组件
const routes = [
  {
    path: '/',              // 当用户访问根路径时
    name: 'Home',           // 给路由起个名(方便后续调用)
    component: HomePage     // 展示HomePage组件
  },
  {
    path: '/about',
    name: 'About',
    component: AboutPage
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),  // 使用HTML5历史模式(路径更优雅)
  routes
})

export default router
4. 启动传送门:在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')

三、打造你的导航菜单:就是那么简单!

在App.vue中放置“传送锚点”
<template>
  <div id="app">
    <!-- 导航菜单 - 就像饭店的菜单目录 -->
    <nav class="navbar">
      <router-link to="/" class="nav-link">🏠 首页</router-link>
      <router-link to="/about" class="nav-link">👨‍💼 关于我们</router-link>
    </nav>
    
    <!-- 内容展示区 - 根据URL动态变化的“餐桌” -->
    <router-view></router-view>
  </div>
</template>
<style>
.navbar {
  background: #2c3e50;
  padding: 1rem;
}
.nav-link {
  color: white;
  margin: 0 1rem;
  text-decoration: none;
}
/* 当前选中菜单的高亮效果 */
.router-link-active {
  color: #42b983;
  font-weight: bold;
}
</style>

四、高级玩法:让路由“骚”起来

1. 动态路由:像变色龙一样自适应

比如用户访问/user/123时,要显示ID为123的用户信息:

// router/index.js 中添加
{
  path: '/user/:id',  // :id 是动态参数
  name: 'User',
  component: UserProfile
}

在UserProfile.vue中获取参数:

<template>
  <div>
    <h2>用户ID: {{ userId }}</h2>
  </div>
</template>
<script>
export default {
  computed: {
    userId() {
      // 从路由参数中获取id
      return this.$route.params.id
    }
  }
}
</script>
2. 编程式导航:不用点击也能跳转

有时候需要在代码中控制跳转,比如提交表单后:

<script>
export default {
  methods: {
    submitForm() {
      // 假装提交表单...
      alert('提交成功!')
      
      // 然后用代码跳转到首页
      this.$router.push('/')
      // 或者 this.$router.push({ name: 'Home' })
    }
  }
}
</script>
3. 路由守卫:给页面加个“保安”

想要某些页面需要登录才能访问?安排!

// 在router/index.js中添加全局守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('token') // 假设用token判断登录
  
  if (to.name === 'User' && !isLoggedIn) {
    // 如果要去用户页面但未登录,强制跳转到登录页
    next('/login')
  } else {
    next() // 放行
  }
})
4. 懒加载:让首屏加载更快

当页面很多时,可以按需加载:

// 原来的写法:一次性加载所有组件
// import AboutPage from '../components/AboutPage.vue'

// 懒加载写法:只有访问/about时才加载
{
  path: '/about',
  name: 'About',
  component: () => import('../components/AboutPage.vue')
}

五、完整示例:一个极简博客系统

下面是一个可直接运行的示例(需要创建对应vue文件):

项目结构:

src/
├── components/
│   ├── HomePage.vue
│   ├── AboutPage.vue  
│   └── PostPage.vue
├── router/
│   └── index.js
└── App.vue

HomePage.vue:

<template>
  <div class="home">
    <h1>📝 我的博客</h1>
    <ul>
      <li @click="goToPost(1)">第一篇:Vue Router真香!</li>
      <li @click="goToPost(2)">第二篇:前端路由原理揭秘</li>
    </ul>
  </div>
</template>
<script>
export default {
  methods: {
    goToPost(id) {
      this.$router.push(`/post/${id}`)
    }
  }
}
</script>

PostPage.vue:

<template>
  <div class="post">
    <button @click="$router.back()">← 返回</button>
    <h2>文章{{ postId }}内容...</h2>
    <p>这里是文章的详细内容</p>
  </div>
</template>
<script>
export default {
  computed: {
    postId() {
      return this.$route.params.id
    }
  }
}
</script>

更新router/index.js:

const routes = [
  { path: '/', name: 'Home', component: () => import('../components/HomePage.vue') },
  { path: '/about', name: 'About', component: () => import('../components/AboutPage.vue') },
  { path: '/post/:id', name: 'Post', component: () => import('../components/PostPage.vue') }
]

六、常见踩坑指南

  1. 路由不生效?
    • 检查main.js里有没有app.use(router)
    • 检查App.vue里有没有<router-view>
  1. 动态路由参数获取不到?
    • 确保路由配置是path: '/user/:id'(有冒号)
    • 组件内用this.$route.params.id获取
  1. 生产模式刷新404?
    • 这是服务器配置问题,需要在服务器将所有路由指向index.html

七、总结

恭喜!你现在已经掌握了Vue Router的核心玩法。记住:

  • 🎯 路由配置就像地图,告诉Vue什么路径显示什么组件
  • 🔗 router-link是导航菜单,比<a>标签更优雅
  • 🖥️ router-view是内容展示框,会根据URL自动变化
  • 🚀 进阶功能让应用更强大,按需学习使用

单页面应用的丝滑体验,绝对是提升产品逼感的利器。现在就把代码跑起来,体验那种“指哪打哪”的畅快感吧!


彩蛋:试着在你的About页面添加一个“悄悄返回”按钮,用this.$router.go(-1)实现,感受一下编程式导航的乐趣吧!😉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

值引力

持续创作,多谢支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值