Vue3--Vue Router详解--学习笔记

51 篇文章 2 订阅

1. 认识vue-router

Angular的ngRouter
React的ReactRouter
Vue的vue-router

Vue Router 是Vue.js的官方路由:

  • 它与Vue.js核心深度集成,让Vue.js构建单页应用(SPA)变得非常容易;
  • 目前Vue路由最新的版本是4.x版本。

vue-router是基于路由和组件的

  • 路由用于设定访问路径,将路径和组件映射起来
  • 在vue-router的单页面应用中,页面的路径的改变就是组件的切换

安装Vue Router

npm install vue-router

2. 路由的基本使用

App.vue

<template>
   <div>
    <div>app</div>
    <router-link to="/home">首页</router-link>
    <router-link to="/about">关于</router-link>
    <router-view></router-view>
   </div>
</template>

<script>

</script>

<style>

</style>

router/index.js

import { createRouter,createWebHashHistory,createWebHistory } from "vue-router";

import Home from '../Views/Home.vue'
import About from '../Views/About.vue'
// 创建一个路由:映射关系
const router = createRouter({
  // 指定采用的模式  hash
  // history:createWebHashHistory(),
  // 使用history模式
  history:createWebHistory(),
  routes:[
    {path:'/',redirect:'/home'},
    {
      path:"/home",
      component:Home
    },
    {
        path:"/about",
        component:About
    }
  ]
})

export default router

Home.vue

<template>
  <div>
   home
  </div>
</template>

<script>
  export default {
    // name:"Home"
  }
</script>

<style scoped>

</style>

About.vue

<template>
  <div>
    About
  </div>
</template>

<script>
  export default {

  }
</script>

<style scoped>

</style>

3.路由模式 (history和hash)

   // 指定采用的模式  hash
   history:createWebHashHistory(),
  // 使用history模式
  history:createWebHistory(),

4. 不记录历史(replace)

<router-link to="/about" replace>关于</router-link>

5. to属性绑定对象

    <router-link :to="{path:'/about'}" replace>关于</router-link>

6. 所在路由样式修改

   .router-link-active{
      color: red;
      font-size: 30px;
   }

设置默认选中class (active-class)

<router-link :to="{path:'/about'}" active-class="link-active">关于</router-link>

7. 路由的懒加载和其他属性

分包处理

const Home = () => import("../Views/Home.vue");
const About = () => import("../Views/About.vue");

分包处理后,不知道那个文件编译打包的,我们可以用魔法注释 (/ webpackChunkName:‘about’ /)
在这里插入图片描述

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

8.获取参数

在template中获取

{{  $route.params.id }}

在compistion-api中获取

<script setup>
  import { useRoute,onBeforeRouteUpdate } from 'vue-router';
  const route = useRoute();
  console.log(route.params.id)

  // 获取route跳转id (路由守卫)
  onBeforeRouteUpdate((to,from)=>{
    console.log("from:",from.params.id)
    console.log("to:",to.params.id)
  })
</script>

在options-api中获取id

this.$route.params.id

9.路由不存在

router/index.js

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

Notfound.vue

<template>
  <div>
    您的页面没找到{{ $route.params.pathMatch }}
  </div>
</template>

<script>
  export default {

  }
</script>

<style scoped>

</style>

10.编程式路由跳转的使用

<template>
     <!-- 其他元素调整 -->
    <span @click="go_home">首页</span>
    <button @click="go_about">关于	    </button>
</template>
<script setup>
   import { useRouter } from 'vue-router';
   const router = useRouter()
   // 监听元素点击
   function go_home(){
      // 调整到首页
      // router.push('/home')
      router.push({
         // name:"home"
         path:'/home'
      })
   }

   function go_about(){
      // 调整到关于
      router.push({
         path:'/about',
         query:{
            name:'why',
            age:18
         }
      })
   }
</script>

options-api写法

<script>
   export default{
      methods:{
         go_home:function(){
            // 调整到首页
            // router.push('/home')
            this.$router.push({
               // name:"home"
               path:'/home'
            })
         },
         go_about:function(){
            // 调整到关于
            this.$router.push({
               path:'/about',
               query:{
                  name:'why',
                  age:18
               }
            })
         }
      }
   }
</script>

页面的前进和后退

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

const router = useRouter();
function back(){
  // router.back()
  //  router.forward()

  // go(delta)
  // go(1) -> forward();
  // go(-1) -> back()
  router.go(-1)
}
</script>

11. 动态添加路由

动态添加路由
router/index.js

let isAdmin = true
if(isAdmin){
  // 一级路由
  router.addRoute({
    path:"/admin",
    component:()=>import("../Views/Admin.vue")
  })
  // 添加vip页面
  router.addRoute("home",{
    path:"vip",
    component:()=>import('../Views/HomeVip.vue')
  })
}

删除路由有以下三种方式:

  • 方式一:添加一个name相同的路由
    在这里插入图片描述

  • 方式二:通过removeRoute方法,传入路由的名称
    在这里插入图片描述

  • 方式三:通过addRoute方法的返回值回调

在这里插入图片描述
路由的其他方法补充

  • router.hasRoute():检查路由是否存在。
  • router.getRoutes():获取一个包含所有路由记录的数组。

12. 路由导航守卫

vue-router提供的导航守卫主要用来通过跳转或取消的方式守卫导航
全局的前置守卫beforeEach是在导航触发时会被回调的:
它有两个参数:

  • to:即将进入的路由Route对象;
  • from:即将离开的路由Route对象;

它有返回值:

  • false:取消当前导航
  • 不返回或者undefined:进行默认导航
  • 返回一个路由地址:
    1. 可以是一个string类型的路径
    2. 也可以是一个对象,对象中包含path,query,params等信息
      可选的第三个参数:next(不推荐使用)
    • 在Vue2中我们是通过next函数来决定如何进行跳转的;
    • 但是在Vue3中我们是通过返回值来进行控制的,不再推荐使用next函数,这是因为开发中很容易调用多次next;

Vue-Router还提供了很多其他守卫函数,目的都是在某一个时刻给予我们回调,让我们可以更好的控制程序的流程或者功能:
https://next.router.vuejs.org/zh/guide/advanced/navigation-guards.html

我们一起来看一下完整的导航解析流程:

  • 导航的触发
  • 在失活的组件里调用beforeRouteLeave守卫。
  • 调用全局的beforeEach守卫
  • 在重用的组件里调用beforeRouteUpdate守卫
  • 在路由配置里调用beforeEnter
  • 解析一部路由组件
  • 在被激活的beforeResolve守卫
  • 导航被确认
  • 调用全局的afterEach钩子
  • 触发DOM更新
  • 调用beforeRouterEnter守卫中传给next的回调函数,创建好的组件实例会作为回调函数的传入参数。

感谢大家观看,我们下次再见

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

2019ab

你的鼓励就是我的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值