Skip to content

Vue 路由

[!quote] Vue 路由

Vue 路由 可以使用户在应用程序中进行导航时,可以根据 URL 路径加载相应的组件

三大核心

  • VueRouter 路由器类,里面维护了一张路由表【记录了 URL 的哈希片段与组件的对应关系】,它可以根据路由请求在路由视图中渲染出对应的组件
  • <router-link> 请求链接组件,可以指定我们要访问的 URL 哈希片段
  • <router-view> 动态视图组件,在想要展示组件的地方放置标签即可

安装配置

  • 在安装 Vue 脚手架时勾选即可
  • 如果没有勾选,则运行 npm install vue-router

具体操作

  • 定义路由表:在 src/ 下创建 router 文件夹 ,在 router/ 下创建 index.js 文件,并在其中定义
js
import { createRouter, createWebHistory } from 'vue-router'

import mapShow from '@/components/mapShow.vue'
import roadPlan from '@/components/roadPlan.vue'

const routes = [
    {
        path: '/',
        redirect: '/dtzs'
    },
    {
        path: '/dtzs',
        name: 'mapShow',
        component: mapShow
    },
    {
        path: '/lxgh',
        name: 'roadPlan',
        component: roadPlan
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
})

export default router
  • main.js 中引入
js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap';

createApp(App).use(router).mount('#app')
  • 在其他组件中定义 <router-link>
vue
<el-menu-item index="1-1">
	<router-link to="/staff">员工页面</router-link>  //点击则跳转到/staff页面
</el-menu-item>
<el-menu-item index="1-2">
	<router-link to="/form_1">表单页面</router-link>
</el-menu-item>
  • App.vue 中声明 <router-view>
vue
<script setup>
</script>

<template>
  <router-view />
</template>