本文最后更新于22 天前,其中的信息可能已经过时,如有错误请发送邮件到qiqin-chang@qq.com
官网:https://router.vuejs.org/zh/guide/
路由配置:
router/index.js:
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{path: '/', redirect: '/manager/home'},
{path: '/manager', component: ()=>import('../views/Manager.vue'),children:[
{path: 'home', name: 'home',meta:{title:'主页'}, component: () => import('../views/Home.vue'),},
{path: 'test', name: 'test',meta:{title:'测试页'}, component: () => import('../views/Test.vue'),},
]
},
{path: '/404', name: 'NotFound',meta:{title:'404找不到页面'}, component: () => import('../views/404.vue'),},
{path:'/:pathMatch(.*)',redirect:'/404'},
],
})
//beforeEach表示跳转之前的操作
router.beforeEach((to, from, next) => {
document.title = to.meta.title;
next();
})
export default router
路由跳转:
标签式跳转:
<RouterLink to="/test">通过router跳转到Test.vue</RouterLink>
编程式跳转:
导入router:
import router from "@/router/index.js"
跳转:
<el-button type="primary" @click="router.push('/test')">使用push跳转到test页面</el-button>
<el-button type="primary" @click="router.replace('/test')">使用replace跳转到test页面</el-button>
- push:跳转方式-添加路由,跳转后可以返回
- replace:跳转方式-替换路由,跳转后无法返回
返回:
<el-button type="primary" @click="router.back()">返回主页</el-button>
路由传参:
发送:
<!--方式一-->
<el-button type="primary" @click="router.push('/test?id=1&name=chang')">路由传参方式1</el-button>
<!--方式二-->
<el-button type="primary" @click="router.push({path:'/test',query:{id:1,name:'chang'}})">路由传参方式2</el-button>
接收:
import {reactive} from "vue";
import router from "@/router/index.js";
const data = reactive({
id:router.currentRoute.value.query.id,
name:router.currentRoute.value.query.name,
})
console.log('获取到传递过来的id='+data.id);
console.log('获取到传递过来的name='+data.name);
嵌套路由:
{path: '/manager', component: ()=>import('../views/Manager.vue'),children:[
{path: 'home', name: 'home',meta:{title:'主页'}, component: () => import('../views/Home.vue'),},
{path: 'test', name: 'test',meta:{title:'测试页'}, component: () => import('../views/Test.vue'),},
]},
- 父级页面可以通过<RouterView/>展现子级页面内容
- 在嵌套路由中子级路由不需要写前面的 / 会自动添加
路由守卫:
修改网页标题:
//to:用于对跳转之后的对象进行操作
//from:用于对跳转前的对象进行操作
//next():调用该方法后,才能进入下一个钩子
//beforeEach表示跳转之前的操作
router.beforeEach((to, from, next) => {
document.title = to.meta.title;
next();
})
meta:补充路由参数的对象
404页面:
定义404路由:
{path: '/404', name: 'NotFound',meta:{title:'404找不到页面'}, component: () => import('../views/404.vue'),},
{path:'/:pathMatch(.*)',redirect:'/404'}, <!--输入错误时统一到达404页面-->
定义404页面:
<template>
<div style="text-align: center">
<img src="../assets/404.png" alt="">
<div>
<el-button type="primary" style="width: 150px;height: 50px;font-size: 20px" @click="gohome">返回主页</el-button>
</div>
</div>
</template>
<script setup>
import router from "@/router/index.js";
const gohome = () => {
location.href = "/manager/home";
}
</script>
<style scoped>
</style>