当前位置: 移动技术网 > IT编程>开发语言>JavaScript > vue Router——进阶篇

vue Router——进阶篇

2019年05月23日  | 移动技术网IT编程  | 我要评论

vue router——基础篇

1.导航守卫

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

记住参数或查询的改变并不会触发进入/离开的导航守卫。你可以通过观察 $route 对象来应对这些变化,或使用 beforerouteupdate 的组件内守卫

全局前置守卫

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

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

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

每个守卫方法接收三个参数:

  • to: route: 即将要进入的目标 路由对象
  • from: route: 当前导航正要离开的路由
  • next: function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
    • next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)
    • next(false): 中断当前的导航。如果浏览器的 url 改变了 (可能是用户手动或者浏览器后退按钮),那么 url 地址会重置到 from 路由对应的地址。
    • next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: truename: 'home' 之类的选项以及任何用在 router-linkto prop 或 router.push 中的选项。
    • next(error): (2.4.0+) 如果传入 next 的参数是一个 error 实例,则导航会被终止且该错误会被传递给 router.onerror() 注册过的回调。

确保要调用 next 方法,否则钩子就不会被 resolved

举个例子

router.beforeeach((to, from, next) => {
  if(to.name === 'one'){
    next('two')
  }
  next()
})

当我们访问

http://localhost:8080/#/one

时,就会跳到

http://localhost:8080/#/two

全局解析守卫

在 2.5.0+ 你可以用 router.beforeresolve 注册一个全局守卫。这和 router.beforeeach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。

router.beforeeach((to, from, next) => {
  if(to.name === 'one'){
    next('two')
  }
  next()
})

router.beforeresolve((to, from, next) => {
  if(to.name === 'two'){
    next('three')
  }
  next()
})

当我们访问

http://localhost:8080/#/one

时,就会跳到

http://localhost:8080/#/two

然后再跳到

http://localhost:8080/#/three

全局后置钩子

你也可以注册全局后置钩子,然而和守卫不同的是,这些钩子不会接受 next 函数也不会改变导航本身

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

路由独享的守卫

路由

{
  path: '/one',
  name: 'one',
  component: one,
  beforeenter: (to, from, next) => {
    if(to.name === 'one'){
      next('two')
    }
    next()
  }
}

当我们访问

http://localhost:8080/#/one

时,就会跳到

http://localhost:8080/#/two

组件内的守卫

  • beforerouteenter
  • beforerouteupdate (2.2 新增)
  • beforerouteleave
beforerouteenter (to, from, next) {
  // 在渲染该组件的对应路由被 confirm 前调用
  // 不!能!获取组件实例 `this`
  // 因为当守卫执行前,组件实例还没被创建
},
beforerouteupdate (to, from, next) {
  // 在当前路由改变,但是该组件被复用时调用
  // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
  // 由于会渲染同样的 foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
  // 可以访问组件实例 `this`
},
beforerouteleave (to, from, next) {
  // 导航离开该组件的对应路由时调用
  // 可以访问组件实例 `this`
}

beforerouteenter 守卫 不能 访问 this,因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建。

不过,你可以通过传一个回调给 next 来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数。

beforerouteenter (to, from, next) {
  next(vm => {
    // 通过 `vm` 访问组件实例
  })
}

注意 beforerouteenter 是支持给 next 传递回调的唯一守卫。对于 beforerouteupdatebeforerouteleave 来说,this 已经可用了,所以不支持传递回调,因为没有必要了

beforerouteupdate (to, from, next) {
  // just use `this`
  this.name = to.params.name
  next()
}
beforerouteleave
beforerouteleave (to, from , next) {
  const answer = window.confirm('do you really want to leave? you have unsaved changes!')
  if (answer) {
    next()
  } else {
    next(false)
  }
}

这个离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 next(false) 来取消

完整的导航解析流程!!!

  • 导航被触发。
  • 在失活的组件里调用离开守卫。
  • 调用全局的 beforeeach 守卫。
  • 在重用的组件里调用 beforerouteupdate 守卫 (2.2+)。
  • 在路由配置里调用 beforeenter
  • 解析异步路由组件。
  • 在被激活的组件里调用 beforerouteenter
  • 调用全局的 beforeresolve 守卫 (2.5+)。
  • 导航被确认。
  • 调用全局的 aftereach 钩子。
  • 触发 dom 更新。
  • 用创建好的实例调用 beforerouteenter 守卫中传给 next 的回调函数。

2.路由元信息

const router = new vuerouter({
  routes: [
    {
      path: '/foo',
      component: foo,
      children: [
        {
          path: 'bar',
          component: bar,
          meta: { requiresauth: true }
        }
      ]
    }
  ]
})

我们称 routes 配置中的每个路由对象为一个路由记录。路由记录可以是嵌套的,因此,当一个路由匹配成功后,他可能匹配多个路由记录

一个路由匹配到的所有路由记录会暴露为 $route 对象 (还有在导航守卫中的路由对象) 的 $route.matched 数组。因此,我们需要遍历 $route.matched 来检查路由记录中的 meta 字段。

在举个栗子

router.beforeeach((to, from, next) => {
  //判断路由记录是否需要验证登录
  if (to.matched.some(record => record.meta.requiresauth)) {
    //  自己定义的判断登录的方法
    let islogin = getloginstatus()
    if (!islogin()) {
      next({
        // 跳转到登录页
        path: '/login',
        // 登录页需要知道从哪跳过来的,方便登录成功后回到原页面
        query: { redirect: to.fullpath }
      })
    } else {
      next()
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

注意!!!

next一定要执行不然钩子函数不会resolved。

3.滚动行为

使用前端路由,当切换到新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。 vue-router 能做到,而且更好,它让你可以自定义路由切换时页面如何滚动。

注意: 这个功能只在支持 history.pushstate 的浏览器中可用。

当创建一个 router 实例,你可以提供一个 scrollbehavior 方法

const router = new vuerouter({
  routes: [...],
  scrollbehavior (to, from, savedposition) {
    if(to.name === 'bookdetails'){
      return { x: 0, y: 0 }
    }
  }
})

scrollbehavior 方法接收 tofrom 路由对象。第三个参数 savedposition 当且仅当 popstate 导航 (通过浏览器的 前进/后退 按钮触发) 时才可用

当我们访问bookdetails路由的时候,就会回到顶部

当然还有好多,就不一一介绍了,

4.路由懒加载

懒加载也叫延迟加载,即在需要的时候进行加载,随用随载。在单页应用中,如果没有应用懒加载,运用webpack打包后的文件将会异常的大,造成进入首页时,需要加载的内容过多,延时过长,不利于用户体验,而运用懒加载则可以将页面进行划分,需要的时候加载页面,可以有效的分担首页所承担的加载压力,减少首页加载用时。

按需加载

{
  path: '/fruits',
  name: 'fruits',
  component: require('@/components/fruits')  // 非按需加载
}

{
  path: '/fruits',
  name: 'fruits',
  component: require(['@/components/fruits'], resolve)  // 按需加载
}

按需加载会在页面第一次请求的时候,把相关路由组件块的js添加上;非按需加载则会把所有的路由组件块的js包打在一起

import()

  • 推荐使用这种方式(需要webpack > 2.4)
  • webpack官方文档:webpack中使用import() vue官方文档:路由懒加载使用import()
const fruits = () => import('@/components/fruits')
{
  path: '/fruits',
  name: 'fruits',
  component: fruits
}

或者

{
  path: '/fruits',
  name: 'fruits',
  component: () => import('@/components/fruits')
}

把组件按组分块

有时候我们想把某个路由下的所有组件都打包在同个异步块 (chunk) 中。只需要使用 ,一个特殊的注释语法来提供 chunk name (需要 webpack > 2.4)

const foo = () => import(/* webpackchunkname: "group-foo" */ './foo.vue')
const bar = () => import(/* webpackchunkname: "group-foo" */ './bar.vue')
const baz = () => import(/* webpackchunkname: "group-foo" */ './baz.vue')

webpack 会将任何一个异步模块与相同的块名称组合到相同的异步块中

vue router

vue router api

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网