您的位置:首页 > Web前端 > Vue.js

超详细!Vue-Router手把手教程

2021-08-09 11:08 706 查看

TOC

最近在重温vue全家桶,再看一遍感觉记忆更深刻,所以专门记录一下(本文vue-router版本为v3.x)。

1,router-view

<router-view>
是一个功能性组件,用于渲染路径匹配到的视图组件。可以配合
<transition>
<keep-alive>
使用。如果两个一起用,要确保在内层使用
<keep-alive>

<router-view></router-view>
<!--或-->
<router-view name="footer"></router-view>

如果

<router-view>
设置了名称,则会渲染对应的路由配置中
components
下的相应组件。

2,router-link

<router-link>
标签支持用户在具有路由功能的应用中(点击)导航。

属性 类型 说明
to String/Object 目标路由/目标位置的对象
replace Boolean 不留下导航记录
append Boolean 在当前路径后加路径 /a => /a/b
tag String 指定渲染成何种标签
active-class String 激活时使用的Class
<router-link :to="{ path: '/login'}" replace tag="span"></router-link>

3,重定向redirect

根路由重定向到

login

const router = new VueRouter({
routes: [
{ path: '/', redirect: '/login' }
]
})

动态返回重定向目标

const router = new VueRouter({
routes: [
{ path: '/a', redirect: to => {
// 方法接收 目标路由 作为参数
// return 重定向的 字符串路径/路径对象
}}
]
})

4,路由别名

路由访问

/b
时,
URL
会保持为
/b
,但是路由匹配则为
/a

const router = new VueRouter({
routes: [
{ path: '/a', component: A, alias: '/b' }
]
})

5,路由传参props

使用

props
,避免和
$route
过度耦合,这样就可以直接在组件中使用
props
接收参数

5.1,布尔模式

在路由后面写上参数,并设置

props
true

{
path: '/vuex/:id',
name: 'Vuex',
component: () => import('@/view/vuex'),
props: true,
mate: {
title: 'vuex'
}
}

设置跳转需要传递的参数

params

<router-link :to="{name:'Vuex', params: {id: '99999'}}" tag="h1">跳转</router-link>
<!--或者-->
toNext() {
this.$router.push({
name: 'Vuex',
params: {
id: '99999'
}
})
}

在跳转过去的页面,通过

props
或者
this.$params
取参

props: {
id: {
type: String,
default: ''
}
}
<!--或者-->
this.$params.id

5.2,对象模式

在路由中设置

props
为对象,携带静态数据

{
path: '/vuex',
name: 'Vuex',
component: () => import('@/view/vuex'),
props: {
id: '99999'
},
mate: {
title: 'vuex'
}
}

跳转

<router-link :to="{name:'Vuex'}" tag="h1">跳转</router-link>
<!--或者-->
toNext() {
this.$router.push({
name: 'Vuex'
})
}

在跳转过去的页面,通过

props
或者
this.$params
取参

props: {
id: {
type: String,
default: ''
}
}
<!--或者-->
this.$params.id

注意:只适用于静态数据

5.3,函数模式

先在路由中设置

props
Function
return
一个对象,不管是
query
传参还是
params
传参,都可以转为
props

{
path: '/vuex',
name: 'Vuex',
component: () => import('@/view/vuex'),
props: route => ({
<!--query-->
id: route.query.id,
<!--params-->
age: route.params.age
}),
mate: {
title: 'vuex'
}
}

跳转

<router-link :to="{name:'Vuex',query: {id: '99999'}, params:{age:'20'}}" tag="h1">跳转</router-link>
<!--或者-->
toNext() {
this.$router.push({
name: 'Vuex',
query: {
id: '999999'
},
params: {
age: '20'
}
})
}

在跳转过去的页面,通过

props
或者
this.$route.params / this.$route.query
取参

props: {
id: {
type: String,
default: ''
},
age: {
type: String,
default: ''
}
}
<!--或者-->
this.$route.query
this.$route.params

6,路由守卫

路由守卫主要用来通过跳转或取消的方式守卫导航。

6.1,全局前置守卫beforeEach

当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫解析完之前一直处于等待中。

参数 说明
to 即将要进入的目标路由对象
from 当前导航正要离开的路由
next 回调方法

next用法如下

语法 说明
next() 进行下一个钩子
next(false) 中断导航,URL如已改,则重置到from的地址
next('/') 中断当前跳转并到其他地址,可设置路由对象
next(error) 导航终止并传递错误给onError()
const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
// ...
})

6.2,全局解析守卫beforeResolve

2.5.0新增,和

beforeEach
类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。

router.eforeResolve((to, from, next) => {
// ...
})

6.3,全局后置钩子afterEach

后置守卫不会接受

next
函数也不会改变导航本身

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

6.4,路由独享守卫beforeEnter

可以在路由配置上直接定义专属的

beforeEnter
守卫,与全局前置守卫的方法参数是一样的。

const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})

6.5,组件内的守卫

  • beforeRouteEnter

该守卫不能访问

this
,因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建。可以通过传一个回调给
next
来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数。

const Footer = {
template: `...`,
beforeRouteEnter(to, from, next) {
next(vm => {
// 通过 `vm` 访问组件实例
})
}
}
  • beforeRouteUpdate (2.2 新增)

在当前路由改变,但是该组件被复用时调用,可以访问组件实例

this

const Foo = {
template: `...`,
beforeRouteUpdate(to, from, next) {
this.name = to.params.name
next()
}
}
  • beforeRouteLeave

导航离开该组件的对应路由时调用,通常用来禁止用户在还未保存修改前突然离开。可以通过

next(false)
来取消。

const Foo = {
template: `...`,
beforeRouteLeave(to, from, next) {
const answer = window.confirm('确认要离开吗')
if (answer) {
next()
} else {
next(false)
}
}
}

6.6,完整的导航解析流程

  1. 导航被触发。
  2. 在失活的组件里调用
    beforeRouteLeave
    守卫。
  3. 调用全局的
    beforeEach
    守卫。
  4. 在重用的组件里调用
    beforeRouteUpdate
    守卫 (2.2+)。
  5. 在路由配置里调用
    beforeEnter
  6. 解析异步路由组件。
  7. 在被激活的组件里调用
    beforeRouteEnter
  8. 调用全局的
    beforeResolve
    守卫(2.5+)。
  9. 导航被确认。
  10. 调用全局的
    afterEach
    钩子。
  11. 触发
    DOM
    更新。
  12. 调用
    beforeRouteEnter
    守卫中传给
    next
    的回调函数,创建好的组件实例会作为回调函数的参数传入。

7,路由元信息

定义路由的时候可以配置meta对象字段,用来存储每个路由对应的信息。通过

this.$route.meta
来访问,或者在路由守卫中通过
to.meta
from.meta
访问。

const router = new VueRouter({
routes: [
{
path: '/index',
name: 'Index',
component: () => import('@/view/index'),
meta: {
title: '首页',
rolu: ['admin', 'boss']
}
}
]
})

8,过渡动效

只需要使用

transition
标签包裹住
router-view
标签即可,动画效果可以自己定义,参考
transition
组件的用法。也可以在父组件或者
app.js
中使用
watch
监听
$route
变化,根据不同路由替换
transition
组件的
name
属性,实现不同的动画效。

<transition :name="transitionName">
<router-view></router-view>
</transition>

监听

watch: {
'$route' (to, from) {
const toD = to.path.split('/').length
const fromD = from.path.split('/').length
this.transitionName = toD < fromD ? 'slide-right' : 'slide-left'
}
}

9,滚动行为

当创建

Router
实例时,可以提供一个
scrollBehavior
方法,并接收
to
from
路由对象。第三个参数
savedPosition
只有通过浏览器的前进/后退按钮触发时才可用。

const router = new VueRouter({
mode: 'hash',
routes,
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(savedPosition)
}, 1000)
})
} else {
return { x: 0, y: 0 }
}
}
})

10,完整路由配置

首先导入

Vue
vue-router
,然后使用
router
,定义路由信息集合,每个路由都是一个对象,对象拥有如下属性

属性 类型
path String 组件路径信息
name String 组件命名
component Function 组件
mate Object 元信息
children Object 子路由
redirect String 重定向
props Boolean/Object/Function 参数传递

具体代码如下:

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const routes = [
{
path: '/',
redirect: '/index'
},
{
path: '/index',
name: 'Index',
component: () => import(/* webpackChunkName: "index" */ '@/view/index'),
mate: {
title: '首页',
auth: false
}
},
{
path: '/login',
name: 'Login',
component: () => import(/* webpackChunkName: "login" */ '@/view/login'),
meta: {
title: '登录',
auth: false
},
children: [
{
path: 'children',
name: 'Children',
component: () => import(/* webpackChunkName: "children" */ '@/view/children'),
mate: {
title: '嵌套的子路由',
auth: false
}
}
]
}
]

const router = new VueRouter({
mode: 'hash',
routes
})

export default router

注意:嵌套子路由必须在被嵌套的页面放置

<router-view>
标签。

如果看了觉得有帮助的,我是@鹏多多,欢迎 点赞 关注 评论;END

公众号

往期文章

个人主页

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: