Vue Router 快速入门

Vue Router 提供 Vue 应用的路由功能,简单理解就是页面跳转,是单页面的页面跳转。Vue Route 比较容易上手,需要理解几个关键的概念:

  • Route:单签路由,当前的URL
  • Router:Vue Router 实例,在main.ts 中的创建的那个 Router
  • < RouterView />:选在组件的标签,每次跳转都会显示对应的组件,RouterView 就是定义在路由配置中的组件
  • 路由配置文件:url 对应组件,参数定义等等
  • 路由守卫:路由的监听器,可以在进入和离开 URL 时添加业务逻辑,例如权限检查

创建一个测试项目

npm create vue@latest通过该命令创建一个项目,根据提示选择即可。

创建路由

router/index.ts定义了路由的配置信息,根据自己的需要进行修改

复制代码
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import TestView from '@/views/TestView.vue'
import TestGrid from '@/views/TestGrid.vue'
import FormView from '@/views/FormView.vue'
import SlotView from '@/views/slots/index.vue'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/test',
      name: 'test',
      component: TestView,
    },
    {
      path: '/testGrid',
      name: 'TestGrid',
      component: TestGrid,
    },
    {
      path: '/form',
      name: 'form',
      component: FormView,
    },
    {
      path: '/slot',
      name: 'slot',
      component: SlotView,
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
  ],
})

export default router

初始化路由

首先在 App.vue中添加 RouterView,

复制代码
// Path: src/App.vue
<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'

</script>

<template>
  <RouterView />
</template>

<style scoped>
</style>

main.ts使用 router

复制代码
import { createApp } from 'vue'
import { createPinia } from 'pinia'

import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/reset.css';
import App from './App.vue'
import router from './router'
import {
    PieChartOutlined,
    MailOutlined,
    DesktopOutlined,
    InboxOutlined,
    AppstoreOutlined,
  } from '@ant-design/icons-vue';

const app = createApp(App)



app.use(createPinia())
app.use(router)
app.use(Antd)
app.component('PieChartOutlined', PieChartOutlined)


app.mount('#app')

路由匹配

通过上面几步简单的路由就可以实现了,如果需要传递参数,需要对路由配置进行修改。添加ID参数:

复制代码
    {
      path: '/testGrid/:id',
      name: 'TestGrid',
      component: TestGrid,
    },

template 中获取参数

复制代码
  <div class="top">
      {{ $route.params.id }}
  </div>

如果想在 script 中获取参数,可以 useRoute hooks

复制代码
<script setup lang="ts">
import align from "dom-align";
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";


const route = useRoute()

onMounted(()=>{
  console.log(route.params.id)
})

</script>

路由守卫

进入路由之前添加业务逻辑

复制代码
router.beforeEach((to, from) => {
  // ...
  // explicitly return false to cancel the navigation
  if (to.name === "form")
  {
    return {name:"home"}
  }
  
})

总结

Vue 路由是管理单页面路由的组件,只要使用了 Router,整个应用的路由和渲染就由 Router 接管了,正确的渲染组件必须使用 RouterView。本文只是介绍了Router 中的几个重点的概念,如需使用更复杂的功能,可以参考 Vue Router 官网,或者使用豆包、DeepSeek 等模型进行编写。

相关推荐
摸鱼的春哥30 分钟前
Agent教程14:记忆才是Agent开发的核心
前端·javascript·后端
明月_清风32 分钟前
Clipboard API 深度实战:如何同时存入“纯文本”和“富文本”两种格式?
前端·javascript
明月_清风37 分钟前
权限陷阱:为什么你的“点击复制”在某些浏览器或 iframe 里会失效?
前端·javascript
掘金安东尼10 小时前
让 JavaScript 更容易「善后」的新能力
前端·javascript·面试
掘金安东尼10 小时前
用 HTMX 为 React Data Grid 加速实时更新
前端·javascript·面试
灵感__idea12 小时前
Hello 算法:众里寻她千“百度”
前端·javascript·算法
yinuo13 小时前
轻松接入大语言模型API -04
前端
袋鼠云数栈UED团队14 小时前
基于 Lexical 实现变量输入编辑器
前端·javascript·架构
cipher14 小时前
ERC-4626 通胀攻击:DeFi 金库的"捐款陷阱"
前端·后端·安全
UrbanJazzerati14 小时前
非常友好的Vue 3 生命周期详解
前端·面试