【Vue-Router】全套路由学习笔记

信息来源:《尚硅谷Vue2.0+Vue3.0全套教程丨vuejs从入门到精通》

一、路由简介

1、类比

  • Vue-Router 类似生活中的路由器,有汇总多对 key:value 的功能
    在这里插入图片描述

2、定义

(1)vue-router

  • vue的一个插件库,专门用来实现 SPA 应用

(2)SPA

  • 单页 Web 应用(SAP:single page web application)
  • 整个应用只有一个完整页面
  • 点击页面导航链接不刷新页面,仅页面局部更新
  • 数据通过 ajax 请求获取

(3)路由

  • 一个路由时一组映射关系(key-value)
    • key:路径
    • value:component(前端)/ function(后端)
      在这里插入图片描述

二、路由基本使用

  • 安装 vue-router,命令:npm i vue-router@3/4 (vue2 仅支持vue-router3,vue3 仅支持vue-router4)

1、项目入口文件 main.js

  • 引入 VueRouter/router 并使用
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router' //引入 VueRouter 
import router from './router' //引入 router 
Vue.use(VueRouter) //使用 VueRouter 

Vue.config.productionTip = false

new Vue({
  router, //路由器添加到 vm
  render: h => h(App)
}).$mount('#app')

2、路由器 router

  • 所有路由结构汇总到路由器 router/index.js
// 创建整个应用的路由器
import VueRouter from 'vue-router'
// 引入组件
import Home from '../pages/Home'
import About from '../pages/About'

//创建并暴露路由器
export default new VueRouter({
  routes:[
    {
      path:'/home',
      component:Home,
    },
    {
      path:'/About',
      component:About
    }
  ]
})

3、组件

  • 分别构建页面渲染结构并使用组件/路由标签
  • 通过切换,“隐藏”的路由组件默认被销毁,需要时再挂载
  • $route 属性每个组件独有,存储自身路由信息(路由规则)
  • $router 属性每个组件共享, 整个应用仅一个 router(路由跳转)
分类App.vuecomponentpages
特点组件汇总一般组件路由组件
操作引用、注册、写标签;渲染路由标签亲自引用、注册、写标签通过路由器引入、渲染

(1)router-link

  • 本质:代替 a 标签实现页面跳转
<router-link 
to="/about" //链接跳转位置
active-class="active" //active 切换
>
About
</router-link >
  • 历史模式:控制路由跳转时操作浏览器历史记录的模式
模式pushreplace
特点追加历史替换当前记录
开启默认模式<router-link replace ...></router-link>

(2)router-view

  • 指定组件的呈现位置
<router-view></router-view>

(3)keep-alive

  • 缓存路由组件,让不展示的路由组件保持挂载,不被销毁
  • 在父组件的子组件呈现位置添加,用 include 属性阻止所有或某些子组件销毁
<keep-alive include="News"> //父组件内操作,include=“需要缓存的子组件”
   <router-view/> //子组件呈现位置
</keep-alive>

<keep-alive :include=["News", "Message",...]> //父组件内操作,:include=“多个需要缓存的子组件”
   <router-view/> //子组件呈现位置
</keep-alive>

三、嵌套(多级)路由

1、配置规则

  • 使用 children 配置子级路由,注意子路径不可添加斜杠 “/”
routes:[
    {
      path:'/About',
      component:About
    },
    {
      path:'/home',
      component:Home,
      children:[ //通过children 配置子级路由
        {
          path:'message', //子路径不可添加斜杠“/”
          component:Message,
          children:[
            {
              name:'detail', //子路径不可添加斜杠“/”
              path:'detail', //子路径不可添加斜杠“/”
              component:Detail
            }
          ]
        }
      ]

2、跳转方式

  • 普通路由,需要写完整路径
<router-link to="/home/news">News</router-link >
  • 命名路由,简化路径 path,直接用名字跳转
routes:[
  {
    path:'/home',
    component:Home,
    children:[
      {
        name:'news', //命名路由
        path:'news',
        component:News,
      }
    ]
    
<router-link to="news">News</router-link >

四、路由参数

  • 传参的三个步骤:
实施环境router/index.js父组件子组件
步骤配置路由传递参数接收参数
  • 路由组件间传参的两种方式:
分类queryparams
语法$route.query.name$route.params.name

1、query 参数

(1)配置路由

routes:[
    {
      path:'/home',
      component:Home,
      children:[
        {
          path:'message',
          component:Message,
          children:[ //我在这里注册了!!!
            {
              name:'detail', //命名路由
              path:'detail', 
              component:Detail
            }
          ]
        }
      ]

(2)传递参数

<!-- 跳转路由并携带 query 参数,to 的字符串写法 -->
<!-- <router-link :to="`/home/message/detail?id=666&title=大白菜`">跳转</router-link>-->

<!-- 跳转路由并携带 query 参数,to 的对象写法 -->
<router-link :to="{
	//path:'/home/message/detail',
    name:'detail', //支持 path 写法,也支持 name 写法
    query:{
        id:666,
        title:大白菜
    }
}">跳转</router-link>

(3)接收参数

$route.query.id
$route.query.title

2、params 参数

(1)配置路由

routes:[
    {
      path:'/home',
      component:Home,
      children:[
        {
          path:'message',
          component:Message,
          children:[
            {
              name:'detail', //命名路由,且 params 必须由名字引入
              path:'detail/:id/:title', //使用占位符声明接收 params 参数
              component:Detail
            }
          ]
        }
      ]

(2)传递参数

<!-- 跳转路由并携带 params 参数,to 的字符串写法 -->
<!-- <router-link :to="`/home/message/detail?id=666&title=大白菜`">跳转</router-link>-->

<!-- 跳转路由并携带 params 参数,to 的对象写法 -->
<router-link :to="{
    name:'detail', //仅支持 name 写法,path 写法页面无渲染
    query:{
        id:666,
        title:大白菜
    }
}">跳转</router-link>

(3)接收参数

$route.params.id
$route.params.title

五、路由的 props 配置

路由传参中的参数接收极为繁琐,使用路由的 props 配置,让路由组件更方便简洁地收到参数

1、props 对象写法

  • props 的值为对象,该对象中所有 key-value 都会以 props 的形式传给 Detail 组件
  • 写死数据,不能灵活传参,不推荐

(1)配置路由

routes:[
    {
      path:'/home',
      component:Home,
      children:[
        {
          path:'message',
          component:Message,
          children:[
            {
              name:'detail', 
              path:'detail', 
              component:Detail,
              props:{id:666,title:'hello'} //对象写法,传递死数据
            }
          ]
        }
      ]

(2)传递参数

<router-link :to="{
	     path:'/home/message/detail',
	     // name:'detail',
	     query:{
	     // params:{ //支持 query/params
	         id:m.id,
	         title:m.title
	     }
}">
{{m.title}}
</router-link>

(3)接收参数

export default {
        name:'Detail',
        props:['id','title']
    }

2、props 布尔写法

  • props 的值为布尔值,若布尔值为真,则把该路由组件收到的所有 params参数,以 props 的形式传给 Detail 组件

(1)配置路由

routes:[
    {
      path:'/home',
      component:Home,
      children:[
        {
          path:'message',
          component:Message,
          children:[ 
            {
              name:'detail', 
              path:'detail', 
              component:Detail,
              props:true //默认为false
            }
          ]
        }
      ]

(2)传递参数

<router-link :to="{
	         name:'detail',
		     params:{ 
	         id:m.id,
	         title:m.title
	     }
}">
{{m.title}}
</router-link>

(3)接收参数

export default {
        name:'Detail',
        props:['id','title']
    }

3、props 函数写法

  • props 的值为函数,该函数返回的对象中每一组 key-value 都会通过 props传给 Detail 组件(最强大写法)

(1)配置路由

routes:[
    {
      path:'/home',
      component:Home,
      children:[
        {
          path:'message',
          component:Message,
          children:[ 
            {
              name:'detail', 
              path:'detail', 
              component:Detail,
              //第一种写法,传统啰嗦,不推荐
              props($route){
                 return {id:$route.query.id,title:$route.query.title}
              },
              //第二种写法,解构赋值,推荐!!!
              props({query}){ 
          	     return {id:query.id, title:query.title}
              },
              //第三种写法,连续解构赋值,语义化不明确,不推荐
              props({query:{id,title}}){ 
          	     return {id, title}
              }
            }
          ]
        }
      ]

(2)传递参数

<router-link :to="{
	     path:'/home/message/detail',
	     // name:'detail',
	     query:{
	     // params:{ //支持 query/params
	         id:m.id,
	         title:m.title
	     }
}">
{{m.title}}
</router-link>

(3)接收参数

export default {
        name:'Detail',
        props:['id','title']
    }

六、编程式路由导航

  • 不借助<router-link>实现路由跳转,使用路由器 $router 的 API 让路由跳转更灵活

1、历史记录

(1)push

  • 追加历史
<button @click="showPush(m)">push查看</button>
        
methods: {
    showPush(m) {
      this.$router.push({
        name:'detail',
        query: { //也支持params
          id: m.id,
          title: m.title,
        },
      })
    }
  }

(2)replace

  • 替换当前记录
<button @click="showReplace(m)">replace查看</button>

methods: {
   showReplace(m){
     this.$router.replace({
       name:'detail',
       query: { //也支持params
         id: m.id,
         title: m.title,
       },
     })
   }
 }

2、历史操作

(1)前进

<button @click="back">后退</button>

methods:{
            back(){
                this.$router.back()
            }
        }

(2)后退

<button @click="forward">前进</button>

methods:{
            forward(){
                this.$router.forward()
            },
        }

七、路由独有的生命周期钩子

  • mounted()、beforeDestroy() 与 <keep-alive>组合后缓存路由,不触发销毁流程,无法停止定时器
  • 路由组件独有的两个生命周期钩子,捕获路由组件的激活与失活状态
钩子activateddeactivated
触发状态激活失活

八、路由守卫

1、全局守卫

(1)全局前置

  • 全局前置路由守卫,初始化时调用,每次路由切换之前被调用
const router = new VueRouter({
  routes:[
    {
      name:'home',
      path:'/home',
      component:Home,
      meta:{title:'首页'}, 
      children:[
        {
          name:'news',
          path:'news',
          meta:{title:'新闻',isAuth:true}, //自定义的 meta 元属性
          component:News
        },
        {
          name:'message',
          path:'message',
          meta:{title:'消息',isAuth:true},
          component:Message
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next)=>{
  // if(to.path === '/home/news' || to.path === '/home/message'){ //路径判断
  // if(to.name === 'news' || to.name === 'message'){ //名称判断
  if(to.meta.isAuth){ //判断是否需要鉴权
    if(localStorage.getItem('name') === 'admin'){ //本地存储姓名符合才可调用 next() 进行展示
      next()
    }else{alert('姓名有误,请重新核对!')}
  }else{next()}
})

(2)全局后置

  • 全局后置路由守卫,初始化时调用,每次路由切换之后被调用
router.afterEach((to,from)=>{ //无 next()
  document.title = to.meta.title || '梦想岛' //修改网页 title
})

2、独享守卫

  • 独享路由守卫写在 routes 内
  • 与全局后置路由守卫搭配使用
{
name:'news',
path:'news',
meta:{title:'新闻',isAuth:true},
//独享路由守卫
beforeEnter: (to, from, next) => {
	//内容与全局前置一致
	if(to.meta.isAuth){
	   if(localStorage.getItem('name') === 'admin'){
	     next()
	   }else{alert('姓名有误,请重新核对!')}
	}else{next()}
},
component:News
}

3、组件内守卫

  • 组件内守卫与全局后置路由守卫搭配使用

(1)进入守卫

  • 通过路由规则,进入该组件时被调用
beforeRouteEnter(to, from, next) =>{
}

(2)离开守卫

  • 通过路由规则,离开该组件时被调用
beforeRouteLeave(to, from, next) =>{
}

九、路由器工作模式

工作模式hashhistory
地址#号,不美观干净、美观
兼容较好较差
特点三方手机 app 分享地址时,app 严格校验下地址会被标记为不合法应用部署上线时需要后端支持,解决刷新页面服务端404问题

1、hash

  • url 中#及其后面的内容是 hash 值,不包含在 HTTP 请求中,不会带给服务器
    在这里插入图片描述
export default new VueRouter({
  mode:'hash', //哈希模式
  routes:[
  ]
  })

2、history

  • url 中没有明显区分,包含在 HTTP 请求中,会带给服务器,需要后端支持解决 在这里插入图片描述
export default new VueRouter({
  mode:'history', //历史模式
  routes:[
  ]
  })
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值