关于vue.js:超详细VueRouter手把手教程

最近在重温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,布尔模式

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

{
    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,函数模式

先在路由中设置propsFunctionreturn一个对象,不论是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.metafrom.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办法,并接管tofrom路由对象。第三个参数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,残缺路由配置

首先导入Vuevue-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

往期文章

  • 应用nvm治理node.js版本以及更换npm淘宝镜像源
  • 超具体!Vuex手把手教程

个人主页

  • CSDN
  • GitHub
  • 简书
  • 博客园
  • 掘金

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据