**安装:**npm install vue-router@4
router文件夹中的index.js:
import { createRouter, createWebHashHistory } from 'vue-router'
// 导入创建的组件
import Home from '../pages/Home.vue'
import About from '../pages/About.vue'
// 配置路由的映射
const routes = [
{ path: '/home', component: Home },
{ path: '/about', compnent: About}
]
// 创建路由对象
const router = createRoter({
routes,
history: createWebHashHistory()
})
// 导出,在main.js中引入并使用
export default router
main.js:
import { createApp } from 'vue'
import router from './router'
import App from './App.vue'
const app = createApp(App)
app.use(router)
app.mount('#app')
// 简写:链式调用,use本身返回的就是app对象
// createApp(App).use(router).mount("#app")
组件中使用:
<template>
<div class="app">
<p>
<router-link to="/home">首页router-link>
<router-link to="/about">关于router-link>
p>
<router-view>router-view>
div>
template>
路由的默认路径即重定向,第一次打开时默认跳转到该页面。
const routes = [
// 默认路由
// { path: '/', component: Home},
// 重定向
{ path: '/', redirect: '/home' },
{ path: '/home', component: Home },
{ path: '/about', compnent: About}
]
通过导入
import {createRouter, createWebHashHistory, createWebHistory} from 'vue-router'来选择使用history模式还是hash模式。
router-link配置:
<router-link to="/home" active-class="tjx">homerouter-link>
router-link也可以自定义渲染:
<router-link to="/home" v-slot="props" custom>
<button @click="props.navigate">{{props.href}}button>
{props.route}} -->
router-link>
const routes = [
// 默认路由
// { path: '/', component: Home},
// 重定向
{ path: '/', redirect: '/home' },
{
path: '/home', name: "home", component: () => {
return import("../pages/Home.vue") // 路由懒加载:完整写法
}
},
// 路由懒加载:简写
{ path: '/user', component: () => import('../pages/User.vue') }
]
const routes = [
{ path: '/home', name: "home", component: Home},
{
path: '/about', component: About,
meta: {
name: 'tjx',
age: 18
}
}
]
很多时候我们需要将给定匹配模式的路由映射到同一个组件: 例如,我们可能有一个 User 组件,它应该对所有用户进行渲染,但是用户的ID是不同的; 在Vue Router中,我们可以在路径中使用一个动态字段来实现,我们称之为 路径参数;
定义:{ path: '/user/:id', component: User }
跳转:
<template>
<div>
<h2>{{ $route.params.id }}h2>
div>
template>
<script>
import { useRouter } from "vue-router";
export default {
name: "App",
// setup中通过useRouter获取$router,注意不是useRoute
setup() {
const router = useRouter();
console.log(router.params.id)
},
methods: {
console.log(this.$route.params.id)
}
};
</script>
对于哪些没有匹配到的路由,我们通常会匹配到固定的某个页面,比如NotFound的错误页面中,这个时候我们可编写一个动态路由用于匹配所有的页面;
定义:{ path: '/:pathMatch(.*)', component: NotFound }
可以通过 $route.params.pathMatch获取到传入的参数:
Not Found: {{ $route.params.pathMatch }}
{
path: '/home', name: "home", component: () => {
return import("../pages/Home.vue") // 路由懒加载:完整写法
},
children: [
{ path: 'message', component: () => import('../pages/HomeMessage.vue') },
{ path: 'shops', component: () => import('../pages/HomeShops.vue') },
]
}
有时候我们希望通过代码来完成页面的跳转,比如点击的是一个按钮。
<script>
import { useRouter } from "vue-router";
export default {
name: "App",
// setup中通过useRouter获取$router,注意不是useRoute
setup() {
const router = useRouter();
const jumpToAbout = () => {
// 1.传递字符串
// router.push("/about");
// 2.传递对象
router.push({
path: '/about',
query: {
name: 'yn',
age: 18
}
})
// router.replace("/about")
};
return {
jumpToAbout,
};
},
// methods: {
// jumpToAbout() {
// // router对象
// this.$router.push('/about')
// }
// }
};
</script>
通过query的方式传递参数:
jumpJToProfile() {
this.$router.push({
path: '/profile',
query: { name: 'tjx', age: 18}
})
}
在界面中通过 $route.query 来获取参数:
query: {{ $router.query.name }}
// 动态添加路由
const categoryRoute = {
path: '/category',
component: () => import("../pages/Category.vue")
}
router.addRoute(categoryRoute)
// 给一级路由对象home添加二级路由对象
router.addRoute('home', {
path: 'moment',
component: () => import('../pages/HomeMount.vue')
})
router.addRouter({ path: '/about', name: 'about', component: About})
// 这将会删除之前已经添加的路由,因为他们具有相同的名字且名字必须是唯一的
router.addRouter({ path: '/other', name: 'about', component: Home})
router.addRouter({ path: '/about', name: 'about', component: About})
router.removeRoute('about')
const removeRoute = router.addRoute(routeRecord)
removeRoute()
补充:
vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。Vue提供了很多的其他守卫函数,目的都是在某一个时刻给予我们回调,让我们可以更好的控制程序的流程或者功能: https://next.router.vuejs.org/zh/guide/advanced/navigation-guards.html
// 导航守卫 beforEach
// router.beforeEach((to, form) => {
// // to: route对象,即将跳转到的route对象
// // from: route对象,从哪一个路由对象跳转过来的
// // 返回值:1.false 不进行导航 2.undefined或不写返回值:进行默认导航,该去哪去哪 3.字符串:路径,跳转到该路径中去
// console.log();
// return false // 不能跳转
// })