vue-router 两种模式
SPA

单页面应用,顾名思义,但也没,加载页面不会加载整个页面,更新某个容器内内容,更新视图不请求页面,在vue中,vue-router用来实现

hash模式

先看官网介绍:

vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。

类似于服务器路由,通过匹配不同的url路径,进行解析,动态渲染出区域html,但是会出现一个问题,url每次发生变化都会导致页面刷新。
解决思路也很简单,在于改变url时页面不刷新,同过加#,这样后面的hash变化,不会使浏览器向服务器发生请求,而且在每次hash发生变化时,还会触发hashChange方法,通过这个方法,监听hashChange实现部分页面的改变

function matchAndUpdate () {
   // todo 匹配 hash 做 dom 更新操作
}

window.addEventListener('hashchange', matchAndUpdate)
history模式

Html5在14年发布之后,多了两个API:pushState和replaceState,通过这两个api改变url地址也不会发送请求,通过html5的api,url改变不用使用#,不过用户刷新页面的时候,需要服务器支持。把路由重定向到根页面

vue-router使用
动态路由匹配

在vue项目中router.js中经常用到,把组件引入然后渲染。

const User = {
  template: '<div>User</div>'
}

const router = new VueRouter({
  routes: [
    // 动态路径参数 以冒号开头
    { path: '/user/:id', component: User }
  ]
})

其中参数路径使用 :id,参数设置在 this. r o u t e . p a r a m s 中 。 当 使 用 参 数 路 由 时 , 原 来 的 组 件 实 例 会 被 复 用 , 例 如 从 / u s e r / f o o 导 航 到 / u s e r / b a r , ∗ ∗ 因 为 使 用 同 一 组 件 , 这 也 意 味 着 生 命 周 期 的 钩 子 不 会 被 调 用 ∗ ∗ , 复 用 组 件 时 , 想 对 参 数 发 生 变 化 , 需 要 用 到 w a t c h 去 监 听 route.params中。 当使用参数路由时,原来的组件实例会被复用,例如从/user/foo导航到/user/bar,**因为使用同一组件,这也意味着生命周期的钩子不会被调用**,复用组件时,想对参数发生变化,需要用到watch去监听 route.params使/user/foo/user/bar使watchroute

const User = {
  template: '...',
  watch: {
    '$route' (to, from) {
      // 对路由变化作出响应...
    }
  }
}
//或者使用2.2之后的beforeRouteUpdate
const User = {
  template: '...',
  beforeRouteUpdate (to, from, next) {
    // react to route changes...
    // don't forget to call next()
  }
}
嵌套路由

在vue的项目中,通常是多层路由嵌套

<div id="app">
  <router-view></router-view>
</div>

const User = {
  template: `
    <div class="user">
      <h2>User {{ $route.params.id }}</h2>
      <router-view></router-view>
    </div>
  `
}

const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User,
      children: [
        {
          // 当 /user/:id/profile 匹配成功,
          // UserProfile 会被渲染在 User 的 <router-view> 中
          path: 'profile',
          component: UserProfile
        },
        {
          // 当 /user/:id/posts 匹配成功
          // UserPosts 会被渲染在 User 的 <router-view> 中
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
})

先在app.js中第一曾router-view,然后在user中第二层,再使用children进行渲染组件

编程式导航

再vue项目内部,可以通过$router来进行路由访问,例如

//html中
<router-link :to=''> 
//js中
this.$router.push

参数可以是一个字符串路径,或者一个描述地址的对象:

// 字符串
router.push('home')

// 对象
router.push({ path: 'home' })

// 命名的路由
router.push({ name: 'user', params: { userId: 123 }})

// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})

const userId = '123'
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// 这里的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user

//router.go(n)这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)
// 在浏览器记录中前进一步,等同于 history.forward()
router.go(1)

// 后退一步记录,等同于 history.back()
router.go(-1)

// 前进 3 步记录
router.go(3)

// 如果 history 记录不够用,那就默默地失败呗
router.go(-100)
router.go(100)
命名视图

多个路由需要同级展示的时候,不如侧边栏和主内容,这时候需要设置name去识别

//name对应的是组件名字
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>

//在router.js里面
const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        default: Foo,//Foo是组件名字
        a: Bar,//Bar是组件名字
        b: Baz//Baz是组件名字
      }
    }
  ]
})
重定向和别名

通过VueRouter也能进行路由的重定向

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

别名:

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

再vue项目中,路由跳转前要做一些验证,比如在登陆,在权限中。

router.beforeEach

在router.js下面使用,可以放置一个全局的前置守卫

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

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

可以看出有三个参数:

  • to:即将进入目标的路由对象
  • from:要离开的路由
  • next:调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。

next(false): 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。

next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: true、name: 'home' 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。

next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。
路由元信息(meta)

在配置路由的时候,每个路由可以添加一个自定义的meta,用来设置一些状态

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      children: [
        {
          path: 'bar',
          component: Bar,
          // a meta field
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})

如何使用meta呢,在to和from里面可以调用,一个路由匹配到的所有路由记录会暴露为 $route 对象 (还有在导航守卫中的路由对象) 的 $route.matched 数组。因此,我们需要遍历 $route.matched 来检查路由记录中的 meta 字段。

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // 确保一定要调用 next()
  }
})
全局解析守卫(router.beforeResolve) 2.5新增

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

全局后置钩子(router.afterEach)
router.afterEach((to, from) => {
  // ...
})

注册全局后置钩子,然而和守卫不同的是,这些钩子不会接受 next 函数也不会改变导航本身,只是一个抓取钩子。

路由独享守卫
const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})
组件内的守卫

在vue组件中使用

  • beforeRouteEnter
  • beforeRouteUpdate (2.2 新增)
  • beforeRouteLeave
const Foo = {
  template: `...`,
  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,但是可以通过vm来访问,而beforeRouteUpdate 和beforeRouteLeave来说,this已经可用了,所以不支持传递回调

beforeRouteEnter (to, from, next) {
  next(vm => {
    // 通过 `vm` 访问组件实例
  })
}
beforeRouteUpdate (to, from, next) {
  // just use `this`
  this.name = to.params.name
  next()
}
beforeRouteLeave (to, from , next) {
  const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
  if (answer) {
    next()
  } else {
    next(false)
  }
}
完整的导航解析流程
1.导航被触发。
2.在失活的组件里调用离开守卫。
3.调用全局的 beforeEach 守卫。
4.在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
5.在路由配置里调用 beforeEnter。
6.解析异步路由组件。
7.在被激活的组件里调用 beforeRouteEnter。
8.调用全局的 beforeResolve 守卫 (2.5+)。
9.导航被确认。
10.调用全局的 afterEach 钩子。
11.触发 DOM 更新。
12.用创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数。
过度动效 (transition)
单个路由的过度动效

在transition中设置name

const Foo = {
  template: `
    <transition name="slide">
      <div class="foo">...</div>
    </transition>
  `
}
路由切换的过渡

具体可以看vue里面的过渡效果

<!-- 使用动态的 transition name -->
<transition :name="transitionName">
  <router-view></router-view>
</transition>

watch: {
  '$route' (to, from) {
    const toDepth = to.path.split('/').length
    const fromDepth = from.path.split('/').length
    this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
  }
}
数据获取

数据获取分两种,导航前和导航后

//导航前
this.$route.params.id

//导航后
  beforeRouteEnter (to, from, next) {
    getPost(to.params.id, (err, post) => {
      next(vm => vm.setData(err, post))
    })
  },
  // 路由改变前,组件就已经渲染完了
  // 逻辑稍稍不同
  beforeRouteUpdate (to, from, next) {
    this.post = null
    getPost(to.params.id, (err, post) => {
      this.setData(err, post)
      next()
    })
  },

  1. params传参,如果刷新页面数据会被清空
  2. query传参,放在url上,不会清空
Logo

前往低代码交流专区

更多推荐