vue-router 路由的学习笔记

vue-router 路由

对应的学习视频 👉https://www.bilibili.com/video/BV1Zy4y1K7SH?p=117

一、什么是路由

  1. 一个路由就是一组映射关系(key-value)
  2. key是路径,value是function或者component
  3. 前端路由用于展示不同的组件,后端路由用于响应不同的请求

二、使用路由

1. 安装vue-router

1
npm install vue-router@3

注:2022年vue-router默认版本变成4,但是4只能在vue3中用,所以指定vue-router为3版本

2.新建router文件夹,并新建index.js文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// router/index.js
import VueRouter from 'vue-router'
import About from '../components/About'
import Home from '../components/Home'

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

3.引入vue-router

1
2
3
4
5
6
7
8
9
// main.js
import VueRouter from 'vue-router'
import router from './router' //引入刚才创建的路由器
Vue.use(VueRouter)

new Vue({
...
router //在vue实例中加入路由器
})

4.在模版中显示

1
2
3
4
5
6
7
<div id="app">
<router-link active-class="active" to="/home">Home</router-link> //路由
<br>
<router-link to="/about">About</router-link>
<hr>
<router-view></router-view>
</div>

㊙ active-class在路由被激活时,提供一个active类

三、几个注意点

  1. 路由组件一般放在pages文件夹,一般的通用组件就放在components文件夹中
  2. 通过切换路由而隐藏的组件是会被销毁的,需要的时候再重新挂载
  3. 每个组件都有一个$route属性,里面存储着自己的路由信息
  4. 整个应用只有一个router。可以通过组件的$router属性获取到

四、嵌套(多级)路由

  1. 配置嵌套路由

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    routes:[
    {
    path:'/about',
    component:About,
    children:[
    {
    path:'news', //注意,子路由不要在前面加斜杠'/',否则匹配不上
    component:News
    }
    ]
    }
    ]
  2. 跳转的router-link写法

    1
    <router-link to="/about/news">News</router-link> //注意:这里的路径要加上父路由的路径

五、路由携带参数

1. query传递参数的两种写法

第一种:to的字符串写法

1
<router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link>

第二种:to的对象写法

1
2
3
4
5
6
7
8
9
<router-link :to="{
path:'/home/message/detail',
query:{
id:m.id,
title:m.title
}
}">
{{m.id}}
</router-link>

2.组件中接收query参数

1
2
3
4
<ul>
<li>消息编号:{{$route.query.id}}</li>
<li>消息标题:{{$route.query.title}}</li>
</ul>

⚠注意:是$route而不是$router,这两个要分清,不要打错!

3.params参数传递的两种写法

第一种:to的字符串写法

1
<router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>

第二种:to的对象写法

1
2
3
4
5
6
7
8
<router-link :to="{
name:'xiangxi', //只能写name,不能写path
params:{
id:m.id,
title:m.title
}
}">
</router-link>

⚠注意:对象写法只能写name,不能写path

4.组件中接收params参数

先在route规则的路径中声明两个占位符,表示接收参数,参数以占位符的名字命名

⚠不声明占位符,就拿不到参数!!!

1
2
3
4
5
6
7
// router/index.js

children:[{
name:'xiangqing',
path:'detail/:id/:title', //:xx,表示占位符,声明接收params参数
component:Detail
}]

然后直接使用即可

1
2
3
4
<ul>
<li>消息编号:{{$route.params.id}}</li>
<li>消息标题:{{$route.params.title}}</li>
</ul>

六、命名路由

作用:给路由起一个名字,在使用router-link跳转时,简略一点代码

先给路由起名字:

1
2
3
4
5
children:[{
name:'xiangxi',
path:'detail',
component:Detail
}]

使用前:

1
2
3
4
5
6
7
<router-link :to="{
path:'/home/message/detail', //三级路由,path很长,写的麻烦
query:{
id:m.id,
title:m.title
}
}">

使用后:

1
2
3
4
5
6
7
<router-link :to="{
name:'xiangxi', //将path换成name,对应的值是路由的名字
query:{
id:m.id,
title:m.title
}
}">

⚠注意:命名路由的名字,直接写成 to=”xiangxi”是不行的,需要使用to的对象写法! :to=”{name:’xiangxi’}”

七、路由的props属性(三种写法,可以更方便的接受参数)

  • props属性对象写法(用的非常少,因为只能传递死数据)

    该对象中的所有key-value都会以props的形式传给Detail组件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    {
    name:'xiangxi',
    path:'detail/:id/:title',
    component:Detail,
    props:{
    a:1,
    b:'hello'
    }
    }
  • props属性的布尔值写法

    若布尔值为真,那么就会将接收到的所有params参数,以props的形式传给Detail组件

    1
    2
    3
    4
    5
    6
    {
    name:'xiangxi',
    path:'detail/:id/:title',
    component:Detail,
    props:true
    }
  • ✔props属性的函数写法(最强大)

    接收一个$route参数,就可以拿到任何的query或params参数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    {
    name:'xiangxi',
    path:'detail/:id/:title',
    component:Detail,
    props($router){ //高级写法,props({params}){},直接拿到,需要学习es6对象解构赋值
    return {
    id:$router.params.id,
    title:$router.params.title
    }
    }
    }
  • 组件接收参数

    1
    2
    3
    4
    5
    6
    <script>
    export default{
    name:'Detail',
    props:['id','title'] //通过props拿到参数,直接用即可
    }
    </script>

八、router-link的replace历史记录模式

  1. 作用:控制点击router-link跳转时,浏览器历史记录的模式

  2. 浏览器历史记录写入方式有两种,默认是push,不断追加记录,而replace模式,则会不断替换记录

  3. 开启replace 模式的方法:

    1
    <router-link  replace  ......></router-link>

九、编程式路由导航

作用,可是实现无需用户点击router-link,触发代码实现路由的跳转,脱离了router-link的限制,让路由跳转更灵活

  • 实现点击按钮push跳转路由

    1
    2
    <button type="button" @click="pushShow(m)">push查看</button>
    <button type="button" @click="replaceShow(m)">replace查看</button>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    methods:{
    pushShow(m){
    this.$router.push({ //push方式记录历史
    name:'xiangqing', //这里的对象就是跟router-link中的
    params:{ //to的对象写法一模一样的
    id:m.id,
    title:m.title
    }
    })
    },
    replaceShow(m){
    this.$router.replace({ //replace方式
    name:'xiangqing',
    params:{
    id:m.id,
    title:m.title
    }
    })
    }
    }
  • 通过back和forward方法实现浏览器前进和后退

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    <template>
    <div>
    <h1>Vue-Router Demo</h1>
    <button @click="forward">前进</button>
    <button @click="back">后退</button>
    </div>
    </template>

    <script>
    export default{
    name:'Banner',
    methods:{
    back(){
    this.$router.back() //back()相当于点击浏览器的后退键
    },
    forward(){
    this.$router.forward() //forward()相当于点击浏览器的前进键
    }
    }
    }
    </script>
  • go()方法实现任意前进后退步数

    1
    this.$router.go(n)

    当n>0,相当于点了浏览器的n次前进键,当n<0,相当于点了浏览器n次后退键

十、缓存路由组件

  • 场景:用户在A路由组件的input框中输入了一些内容,由于切换路由就会销毁路由组件,所以当他再次切换会A组件时,input输入框里面的东西就会没了

  • 怎么缓存?使用包裹对应的即可,这样切换路由时将不会销毁组件

    1
    2
    3
    4
    5
    6
    7
    8

    <router-link to="/home/news">news</router-link>
    <br>
    <router-link to="/home/message">message</router-link>
    <hr>
    <keep-alive include="News">
    <router-view></router-view>
    </keep-alive>

    注1:使用include=“组件名”可以单独指定哪一个组件被缓存,上面的案例中,本来News和Message组件都将被缓存,但是由于指定了include=“News”,所有Message组件将不会被缓存

    注2:使用数组写法可以缓存多个指定的组件, :include=”[‘News’,’Message’]”,这样就可以缓存News和Message这两个组件

十一、两个路由组件特有的声明周期钩子(路由组件特有的)

activated() : 当路由组件被激活时,执行函数里的代码

deactivated(): 当路由组件没有被激活,被切换走了的时候,执行函数里的代码

十二、路由守卫

官网内容:正如其名,vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。这里有很多方式植入路由导航中:全局的,单个路由独享的,或者组件级的。

大概就是根据一些条件,比如用户权限,或者是否登录进行对路由跳转的限制

全局前置路由守卫–初始化、每次路由切换之前被调用

使用方式

1
2
3
4
5
6
7
8
9
10
// router/index.js

const router = new VueRouter({......})

router.beforeEach((to,from,next)=>{
console.log('@@@')
next()
})

export default router

beforeEach中回调函数的三个参数

  • to:代表想到哪里去
  • from:代表从哪里来
  • next:一个函数,调用之后就可以正常跳转

小案例,实现判断localStorage的一个属性值来跳转

1
2
3
4
5
6
7
8
9
router.beforeEach((from,to,next)=>{
if(localStorage.getItem("isLogin")){
next()
}else{
alert('请先登录')
}
})

//判断条件可以从任何能得到数据的地方拿

路由元信息

作用:向单个路由规则添加一些自定义的信息,配合路由守卫,实现针对性的权限控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// router/index.js
{
path: 'news',
component: News,
meta: {
isAuth: true
}
},
{
path: 'message',
meta:{
isAuth:true
}
},
1
2
3
4
5
6
7
8
9
router.beforeEach((from,to,next)=>{
if(to.meta.isAuth){ //首先判断要跳转的那个路由,是否需要鉴权
if(localStorage.getItem("isLogin")){
next()
}else{
alert('请先登录')
}
}
})

全局后置路由守卫–初始化、每次路由切换之后被调用

使用方法(没有next参数)

1
2
3
4
5
6
7
8
9
// router/index.js

const router = new VueRouter({......})

router.afterEach((from,to)=>{
console.log(from,to)
})

export default router

小案例,实现跳转后,标签页的标题更换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// router/index.js
{
path: 'news',
component: News,
meta: {
isAuth: true,
title:'新闻'
}
},
{
path: 'message',
meta:{
isAuth:true,
title:'消息'
}
},
1
2
3
4
5
// router/index.js
router.afterEach((to,from)=>{
console.log(to,from);
document.title = to.meta.title || '默认标题'
})

独享路由守卫–单个路由规则的控制

使用方法

除了函数名称不一样之外,其余的使用逻辑,跟全局前置路由守卫是一样的!

⚠注意:独享路由守卫,只有前置beforeEnter(),没有后置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// router/index.js

{
path: 'news',
component: News,
meta: {
isAuth: true,
title:"新闻"
},
beforeEnter(to,from,next) {
console.log(to);
console.log(from);
if (localStorage.getItem("isLogin")) {
next();
}
}
}

组件内路由守卫–通过路由规则,进入或离开组件时被调用

当然是写在组件内部的,而且必须是通过路由规则进入,那种注册组件直接写组件标签的不算

beforeRouteEnter(to,from,next)

1
2
3
4
5
6
7
8
9
10
11
12
13
<!--pages/Message.vue-->

<script>
export default{
name:'Message',
......
beforeRouteEnter(to,from,next){
console.log(to,from);
//在next()被调用之前,同样可以写判断权限的逻辑
next();
}
}
</script>

beforeRouteLeave(to,from,next)

⚠注意:如果你在离开的路由守卫中,没有写next(),那么跳转到下一个组件将不会成功,页面无变化

1
2
3
4
5
6
7
8
9
10
11
12
<!--pages/Message.vue-->

<script>
export default{
name:'Message',
......
beforeRouteLeave(to,from,next){
console.log(to,from);
next();
}
}
</script>

十三、history模式和hash模式

两者区别:

  • hash模式,默认的路由模式

    1. 在浏览器的地址栏上会出现杠井号👉/#不是很美观,并且/# 后面的全部内容不会发送给后端服务器
    2. 若将hash模式的地址通过第三方手机app分享,若该app校验严格,则地址会被标记为不合法
    3. 兼容性较好
  • history模式

    1. 在创建路由器对象的时候指定
    2. 浏览器的地址栏上边不显示井号
    3. 兼容性差一点
    4. 需要后端工程师配合,解决刷新导致404的问题
    1
    2
    3
    4
    5
    6
    // router/index.js

    const router = new VueRouter({
    mode:'history', //指定为history模式
    routes:[......]
    })

history模式带来的问题

由于hash模式井号后面的内容不会发送给后端服务器,所有可以随意刷新页面,但是history模式的路由一旦刷新页面,就会将重新请求地址栏中的资源,由于后端没有这些东西,就会报404,

解决history模式带来问题的几种解决方案

  • 后端工程师通过使用相关的库、插件、或者手动处理错误的路径
  • 在nginx代理服务器上进行错误路径的判断

vue-router 路由的学习笔记
http://blog.jingxiang.ltd/2023/03/30/vue-router的学习笔记/
作者
yemangran
发布于
2023年3月30日
许可协议