vue-router实践指南🍓

51 阅读3分钟

本文github地址:JavaScript_Everything 大前端知识体系与面试宝典,从前端到后端,全栈工程师,成为六边形战士


基本思想

设定访问路径,将路径和组件进行映射;页面路径的改变就是组件的切换

快速上手

  1. 创建路由表
import {createRouter, createWebHashHistory} from 'vue-router'

import Home from '../Views/Home.vue'
import About from '../Views/About.vue'

// 创建路由表
const router = createRouter({
    // 指定路由模式
    history: createWebHashHistory(),
    // 存放映射关系
    routes:[
        {path:"/home", component: Home},
        {path:"/about", component: About},
    ]
})

export default router
  1. 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')
  1. 创建两个切换组件:About.vueHome.vue

  2. 需要在App.vue中使用<router-view></router-view>进行占位,作为切换路由时对应组件渲染的位置。

<template>
  <div class="app">
    <Info :name="name" :age="age" ref="infoRef"></Info>
    <router-view></router-view>
  </div>
</template>

路由链接

<template>
  <div class="app">
    <Info :name="name" :age="age" ref="infoRef"></Info>
    <router-view></router-view>
    <div class="nav">
      <!-- 路由链接 -->
      <router-link to="home">首页</router-link>
      <router-link to="about">关于</router-link>
    </div>
  </div>
</template>

配置默认路由

routes:[
    {path:"/", component: Home},
]

路由跳转/重定向

routes:[
    {path:"/", redirect: "home"},
]

history 路由模式

import {createRouter, createWebHistory} from 'vue-router'
const router = createRouter({
    history: createWebHistory(),
}

history 模式下进行跳转,不记录历史

<router-link to="home" replace>首页</router-link>

路由激活时的样式应用

默认样式类为:router-link-active

修改指定应用的激活样式类:

<router-link to="home" active-class="link-active">首页</router-link>

路由懒加载

  1. 利用import的分包机制,不直接引入组件,在组件使用时再动态引入。
  2. 打包时会对组件进行分包处理,减小包体积,加快首屏渲染速度
import {createRouter, createWebHistory} from 'vue-router'

const Home  = () => import(/*webpackChunkName:'home.chunk'*/'../Views/Home.vue')
const About = () => import(/*webpackChunkName:'about.chunk'*/'../Views/About.vue')

// 创建路由表
const router = createRouter({
    // 指定路由模式
    history: createWebHistory(),
    // 存放映射关系
    routes:[
        {path:"/",},
        {path:"/home", component: Home},
        {path:"/about", component: About},
    ]
})

或者:

    routes:[
        {path:"/",},
        {
            path:"/home", 
            component: () => import(/*webpackChunkName:'home.chunk'*/'../Views/Home.vue')
        },
        {
            path:"/about", 
            component: () => import(/*webpackChunkName:'about.chunk'*/'../Views/About.vue')
        },
    ]

动态路由

用途:url/userInfo路径中显式用户 ID 等标识信息

    {
        path:"/user:id",
        component:() => import('../Views/User.vue')
    }

在模板获取动态路由值

<template>
  <div class="user">
    <h1>{{ $route.params.id }}</h1>
  </div>
</template>

在options中获取动态路由值:this.$route.params.id

在setup中获取动态路由值:

<script setup>
import {onBeforeRouteUpdate, useRoute} from 'vue-router'

// 第一次获取
const route = useRoute()
console.log(route.params.id)

// 路由跳转改变后获取
onBeforeRouteUpdate((to, from)=>{
    console.log(to.params.id)
    console.log(from.params.id)
})
</script>

匹配 NotFound 路由

前面路由都匹配不到时,任何路径都会显式NotFound页面

{
    path:"/:pathMatch(.*)",
    component:() => import('../Views/NotFound.vue')
}

若是path:"/:pathMatch(.*)*",会对路径进行解析,得到一个路径解析后的数组

编程式导航

对元素点击等事件进行路由跳转时,可以通过执行回调函数的方式,在函数中进行路由跳转

<template>
  <div class="app">
    <router-view></router-view>
    <div class="nav">
      <!-- 路由链接 -->
      <router-link to="home">首页</router-link>
      <router-link to="about">关于</router-link>
      <span @click="clickUser">我的</span>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'

// 编程式导航
const router = useRouter()
function clickUser(){
  router.push('/about')
}
</script>

跳转时传递参数:

import { useRouter } from 'vue-router'
const router = useRouter()
function clickUser(){
  router.push({
    path:'/about',
    query:{
      name:'flten',
      age:18,
    }
  })
}

跳转之后的url为http://127.0.0.1:5173/about?name=flten&age=18

可以在对应的页面中获取到传递过来的参数

页面中返回

<template>
  <div class="app">
    <button @click="back">返回</button>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
function back(){
    router.back()
    // router.forward()
    // router.go(-1)
    // router.go(1)
}
<script>

路由传递参数的方式

  1. 动态路由
  2. 编程式导航导航query传递参数

路由导航守卫

从一个路由转到另外一个路由时,称为路由导航。但是在这个跳转的中间环节,进行拦截操作,执行判断逻辑决定跳转到哪个路由。

vue-router提供了一系列方法,让我们传入回调函数,决定在跳转的不同阶段进行哪些逻辑处理及跳转处理。

全局前置守卫beforeEach:每次路由跳转都进行登录页面

router.beforeEach((to, from)=>{
    // 返回的路径就是跳转的路径
    if(to.path !== '/login') return '/login'
    // return false //取消当前导航
    // return undefined //不进行处理,默认导航
})

或者返回一个对象,传入更多参数:

router.beforeEach((to, from)=>{
    if(to.path !== '/login'){
        return {
            path: '/login',
            query:{
                source: '/'
            }
        }
    }
})

判断登录状态的示例:

router.beforeEach((to, from)=>{
    const token = localStorage.getItem('token')
    if(!token && to.path === '/order') return '/login'
})

本文github地址:JavaScript_Everything 大前端知识体系与面试宝典,从前端到后端,全栈工程师,成为六边形战士