路由 vue-router

2020-03-17  本文已影响0人  moofyu

this.$router和this.$route的区别是什么?

vue-router 的路由跳转的方法

<router-link to="/" tag="p">耳机频道</router-link>
//to是一个prop.指定需要跳转的路径,也可以使用v-bind动态设置
//tag可以指定渲染成标签,默认是a标签
<router-link to="/" replace>跳转回去</router-link>  
//这样的写法是不会留下历史痕迹,回退键无效
<router-link :to="{ name: 'product', params: { id : 1 }}">User</router-link>
// /product/1
//这里假设 我要跳转product页面并且附带参数id 
//这里定义好了list.id 就是 动态的值
this.$router.push('./product/' + list.id)            // 字符串的方式进行描述
this.$router.push({name : 'product',params: { id : list.id }})  // 命名的路由的方式进行描述
this.$router.push({ path: `/product/${list.id}` })        // 直接定义path类似第一种
//比较常用的跳转路由的方法
//假如是带查询参数
this.$router.push({ path: 'product', query: { id: list.id }})      // /product?id=1

这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。

当你点击 <router-link> 时,这个方法会在内部调用,所以说,点击<router-link :to="..."> 等同于调用 router.push(...)。
值得注意的一点是,如果提供了 path,params 的配置将不会生效

还有一些方法

router.replace   //它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录
router.go(1)    //在浏览器记录里面前进一步,等于history.forward()
router.go(-1)    //后退一步记录,等同于 history.back()
router.go(n)    //浏览器记录前进3步

导航守卫

全局的

路由实例上直接操作的钩子函数,所有路由配置的组件都会触发

路由独享的

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

组件内的

在组件内执行的钩子函数,相当于为配置路由的组件添加的生命周期钩子函数。

<template>
  ...
</template>
export default{
  data(){
    //...
  },
  beforeRouteEnter (to, from, next) {
  },
  beforeRouteUpdate (to, from, next) {
  },
  beforeRouteLeave (to, from, next) {
  }
}
<style>
  ...
</style>
 beforeRouteEnter (to, from, next) {
  // 这里还无法访问到组件实例,this === undefined
  next( vm => {
    // 通过 `vm` 访问组件实例
  })
}

导航守卫回调参数

to:目标路由对象;
from:即将要离开的路由对象;
next:确保要调用 next 方法,否则钩子就不会被 resolved。

执行顺序

当点击切换路由时:

  1. beforeRouterLeave:\color{Blue}{组件路由守卫}
  2. beforeEach:\color{ForestGreen}{全局前置守卫}
  3. beforeEnter:\color{Coral}{路由独享守卫}
  4. beforeRouteEnter:\color{Blue}{组件路由守卫}
  5. beforeResolve:\color{ForestGreen}{全局解析守卫}
  6. afterEach:\color{ForestGreen}{ 全局后置守卫}
  7. beforeCreate:组件生命周期
  8. created:组件生命周期
  9. beforeMount:组件生命周期
  10. mounted:组件生命周期
  11. beforeRouteEnter的next的回调:\color{Blue}{组件路由守卫}
上一篇下一篇

猜你喜欢

热点阅读