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

1次阅读

共计 5561 个字符,预计需要花费 14 分钟才能阅读完成。

最近在重温 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
  • 简书
  • 博客园
  • 掘金
正文完
 0