【Vue】路由

快速入门

1. 安装路由

npm install --save vue-router

2. 定义组件

<template>
  <div>
    <h3>Home</h3>
    <router-link to="/login">Login</router-link>
  </div>
</template>
<script>
export default {};
</script>

3. 定义路由规则

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

export default new VueRouter({
    mode: 'history',
    routes: [
        { path: '/', component: () => import('../views/home.vue') },
        { path: '/login', component: () => import('../views/login.vue') },
    ]
});

4. 在需要显示路由位置放<router-view />

<router-view />

这就完成一个简单路由

深入路由

基础

VueRouter.model :

  • hash(默认):使用 URL 的 hash 来模拟一个完整的 URL
  • history :利用 history.pushState API 来完成 URL 跳转而无须重新加载页面

<router-link> : 路由功能导航,默认生成<a>标签,可以使用tag属性修改生成的标签

<router-view /> : 路由出口,匹配到的路由会在这里渲染

动态路由

通常链接需要带上参数,根据参数显示不同结果

Vue动态路由用":" 匹配路径参数,然后就匹配的参数放入$route.params

1. 定义动态路由,这里需要对路由命名,获取名称和性别

{ path: '/login/:username/:sex', name: 'login', component: () => import('../views/login.vue') },

2. 路由链接 - 需要路由命名

<router-link :to="{ name: 'login',  params: { username, sex } }">Login</router-link>
<!--等价于-->
<router-link to="/login/WilsonPan/1">Login</router-link>

3. 组件获取路由参数

<h3>username : {{ this.$route.params.username }}</h3>
<h3>sex : {{ this.$route.params.sex === 1 ? "男" : "女" }}</h3>

注:除了可以设置路由参数,还可以设置query参数

<router-link :to="{ name: 'login', query: { id: 3 }, params: { username, sex } }">Login</router-link>
<!--等价于-->
<router-link to="/login/WilsonPan/1?id=3">Login</router-link>

组件获取query参数

<h3>id : {{ this.$route.query.id }}</h3>

嵌套路由

一个路由渲染的页面包含另外的路由

1. 定义路由

{
            path: '/', 
            name: 'home', 
            component: () => import('../views/home.vue'), 
            children: [
                { path: '/', component: () => import('../components/ComponentDemo.vue') },
                { path: '/directives', component: () => import('../components/Directives.vue') }

            ]
        }

2. 在需要显示子路由的地方放子路由渲染页面

<router-view />

导航守卫

导航守卫主要用来通过跳转或取消的方式守卫导航,导航守卫有全局的,单个路由的,组件级别,用于未登录控制访问,控制访问等。

全局路由

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

router.beforeEach((to, from, next) => {
  // ...
})
  • to: Route: 即将要进入的目标路由对象
  • from: Route: 当前导航正要离开的路由
  • next: Function: 一定要调用该方法来 **resolve** 这个钩子。执行效果依赖 next 方法的调用参数。

路由独享的守卫

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

组件内的守卫

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`
  }
}

猜你喜欢

转载自www.cnblogs.com/WilsonPan/p/12770411.html