Vue—— vue中的路由

一、Vue中的路由

  vue-router 是 vue 中提供的路由,

1.使用vue-router 的步骤:

(1)导入 vue 文件和 vue-router 文件

<script src="/path/to/vue.js"></script>
<script src="/path/to/vue-router.js"></script>

(2)创建路由实例并配置路由规则

// 路由实例
const router=new VueRouter({
  // 路由规则
  routes:[]
})

(3)将路由实例挂载到vue 实例上

const vm=new VTTCue({
  el:'#app',
  data:{},
  router:router
})

(4)创建路由导航

(5)创建路由占位符

<div >
  <!-- 路由链接 -->
  <router-link to="组件路径"></router-link>
  <router-link to="组件路径"></router-link>
  <!-- 路由占位符 -->
  <router-view></router-view>
</div>

二、路由的模式

  vue 中路由的模式有两种:hash模式,history模式,可以在路由配置文件中通过 mode 字段来指定当前使用的路由模式。默认是hash 模式。

  history 模式容易发生一个问题,如果是页面刷新的时候容易发生404错误。

  详细可以看(https://www.cnblogs.com/zhilili/p/14721911.html)

三、路由中的参数传递

  vue-router 中的路由跳转和参数传递主要有三种:

(1)通过动态路由方式

// 配置路由规则
const routes=[
  {
    path:'/detail/:id',
    name:"Detail",
    component:Datail
  }
];
// 路由跳转页面时候
var id=1;
this.$router.push('/detail/'+id)

// 获取路由传递的参数
this.$route.params.id

  页面刷新参数不会消失

  可以在路由中设置多段参数,如下

模式匹配的路径$route.params
/user/:username/user/even{username:'evan'}
/user/:username/post/:post_id/user/even/post/123{username:'even',post_id:'123'}

(2)通过query 属性传值

// 配置路由规则
const routes=[
  {
    path:'/detail',
    name:"Detail",
    component:Datail
  }
];
// 路由跳转页面时候
this.$router.push({
  path:'/detail',
  query:{
    name:'张三',
    id:1
  }
})

// 获取路由传递的参数
this.$route.query.id
this.$route.query.name

  页面刷新参数不会消失

(3)通过params 属性传值

// 配置路由规则
const routes=[
  {
    path:'/detail',
    name:"Detail",
    component:Datail
  }
];
// 路由跳转页面时候
this.$router.push({
  name:'Detail',
  params:{
    name:'张三',
    id:1
  }
})

// 获取路由传递的参数
this.$route.params.id
this.$route.params.name

  页面刷新参数会消失。

四、动态路由

  我们经常需要把某种模式匹配到的所有路由,全都映射到同个组件。例如,我们有一个 User 组件,对于所有 ID 各不相同的用户,都要使用这个组件来渲染。那么,我们可以在 vue-router 的路由路径中使用“动态路径参数”(dynamic segment) 来达到这个效果:

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

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

  像/user/foo 和 /user/bar 都将映射到相同的组件里面。

  一个路由参数使用冒号“:”,当匹配一个路由的时候,它后面的参数就会被匹配到 this.$route.params 里面,我们可以通过它来获取里面指定的参数。

动态路由参数的变化:

  注意:如果是使用路由参数的时候,例如从 /user/foo 到/user/bar 的时候,原来的组件实例会被复用,因为他们两个路径对应的都是同一个路由组件,比起组件销毁重建,复用更有效率,这就意味着user 组件的生命周期钩子将不会被调用,如果想要获取到变化的路由参数,可以使用watch监听属性来监听路由的变化,或者使用新增的组件内的路由钩子函数来获取变化的路由参数。

(1)使用watch监听属性来监听路由的变化:

const User = {
  template: '...',
  watch: {
    $route(to, from) {
      // 对路由变化作出响应...
    }
  }
}

(2)或者使用2.2中新增的路由导航钩子

const User = {
  template: '...',
  beforeRouteUpdate(to, from, next) {
    // react to route changes...
    // don't forget to call next()
  }
}

五:路由中的生命周期钩子

路由的导航守卫分为三种:全局路由导航守卫,单个路由导航守卫,组件内的导航守卫。

(1)全局路由导航守卫

 * 前置路由导航守卫router.beforeEach():

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

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

  每个守卫接受三个参数:

    to:是一个route对象,即将要进入的目标路由对象。

    form:也是一个route对象,表示当前正要离开的路由。

    next:是一个函数,一定要调用该方法来resolve 这个钩子。

  确保 next 函数在任何给的的导航说守卫中都被严格调用一次,他可以出现多余一次,但是只能在所有的逻辑路由都不重叠的情况下,否则钩子都不会被解析或者报错,如下;

// BAD
router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  // 如果用户未能验证身份,则 `next` 会被调用两次
  next()
})


// GOOD
router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  else next()
})

 * 后置路由导航守卫router.afterEach((ro,from)=>{})

(2)单个路由导航守卫:

 可以直接在路由配置上直接定义 beforeEnter 守卫:

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

(3)组件内的导航守卫:

  * 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,因为守卫在导航确认前被调用,因此即将登场的新组件还没有被创建。

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

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

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

完整的导航解析流程:

- 导航被触发。

- 在失活的组件中调用 beforeRouteLeave 守卫

- 调用全局的 beforeEach 守卫。

- 在重复的组件中调用 beforeRouteUpdate 守卫

- 在路由配置中调用 beforeEnter.

- 解析异步路由组件

- 在被激活的组件里面调用 beforeRouteEnter

- 调用全部的 beforeResolve 守卫

- 导航被确认

- 调用全局的afterEach 钩子

- 触发 DOM 更新

- 调用 beforeRouteEnter 守卫传递给 next 的回调函数,创建好的组件实例会在 next 的回调函数里面被调用。