vue3 setup router的使用教程
文章目录
setup中没有this,所以我们需要引入vue-router的实例,然后通过实例来操作路由。
操作和之前有一些差异,所以这里记录一下。
1. 安装
npm install vue-router
2. 使用(创建路由实例)
import {
createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/',
name: 'Home',
component: Home
}]
const router = createRouter({
/**
* 这里可以配置路由模式
*
* @description 1. hash模式
@example import { createRouter, createWebHashHistory } from 'vue-router'
history: createWebHashHistory(),
* @description 2. history模式
* 如下:
*/
history: createWebHistory(),
routes,
})
export default router
3. 路由跳转
请先引入router实例,接下来的操作都是基于我们创建的router实例。
import router from './router'
3.1 通过router-link标签跳转
<router-link to="/">Home</router-link>
3.2 通过js代码跳转
import router from './router'
// 通过query传参
router.push({
path: '/about',
query: {
id: 1
}
})
// 通过params传参
router.push({
path: '/about',
params: {
id: 1
}
})
// 或者
router.push('/about?id=1')
4. 接收参数
4.1 通过query接收参数
import router from './router'
onMounted(() => {
console.log(router.currentRoute.value.query.id)
})
4.2 通过params接收参数
import router from './router'
onMounted(() => {
console.log(router.currentRoute.value.params.id)
})
5. 路由守卫
5.1 全局守卫
import router from './router'
router.beforeEach((to, from, next) => {
// to: 即将要进入的目标 路由对象
// from: 当前导航正要离开的路由
// next: 调用该方法后,才能进入下一个钩子
next()
})
5.2 路由独享守卫
const routes = [
{
path: '/',
name: 'Home',
component: Home,
beforeEnter: (to, from, next) => {
next()
}
}]
5.3 组件内守卫
import {
onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'
onBeforeRouteLeave((to, from, next) => {
console.log(to, from)
next()
})
onBeforeRouteUpdate((to, from, next) => {
console.log(to, from)
next()
})
6. 路由懒加载
const routes = [
{
path: '/',
name: 'Home',
component: () => import('../views/Home.vue')
}]
7. 路由嵌套
const routes = [
{
path: '/',
name: 'Home',
component: Home,
children: [
{
path: 'about',
name: 'About',
component: () => import('../views/About.vue')
}
]
}]
8. 路由别名
const routes = [
{
path: '/',
name: 'Home',
component: Home,
alias: '/home'
}]
9. 路由重定向
const routes = [
{
path: '/',
name: 'Home',
component: Home,
redirect: '/home'
}]
10. 路由滚动行为
const router = createRouter({
history: createWebHistory(),
routes,
scrollBehavior(to, from, savedPosition) {
// to: 即将要进入的目标 路由对象
// from: 当前导航正要离开的路由
// savedPosition: 滚动条的坐标
return {
x: 0,
y: 0
}
}
})
11. 获取所有路由
import router from '@/router';
console.log(router.options.routes)
12. 获取当前路由
import router from '@/router';
console.log(router.currentRoute.value)