构建vue-router知识体系(二)-路由的使用步骤

90 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第28天,点击查看活动详情

使用 vue-router 的步骤

  • 第一步:创建路由组件的组件;
  • 第二步:配置路由映射:组件和路径映射关系的 routes 数组;
  • 第三步:通过 createRouter 创建路由对象,并且传入 routes 和 history 模式;
  • 第四步:使用路由:通过<router-link><router-view>

尝试写一个路由

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>vue</title>
</head>
<body>
    <div id="app">
        <!-- router-view是一个全局组件,可以全局使用  -->
       <router-view></router-view>
    </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://unpkg.com/vue-router@2.0.0/dist/vue-router.js"></script>
<script>
    // 0. 如果使用模块化机制编程,导入Vue和VueRouter,要调用 Vue.use(VueRouter)

    // 1. 定义 (路由) 组件。
    // 可以从其他文件 import 进来
    const Foo = { template: '<div>foo</div>' }
    const Bar = { template: '<div>bar</div>' }

    // 2. 定义路由
    // 每个路由应该映射一个组件。 其中"component" 可以是
    // 通过 Vue.extend() 创建的组件构造器,
    // 或者,只是一个组件配置对象。
    // 我们晚点再讨论嵌套路由。
    const routes = [
    	{ path: '/foo', component: Foo },
    	{ path: '/bar', component: Bar }
    ]
    // 3. 创建 router 实例,然后传 `routes` 配置
    // 你还可以传别的配置参数
    const router = new VueRouter({
    	routes // (缩写) 相当于 routes: routes
    })

    // 4. 创建和挂载根实例。
    // 记得要通过 router 配置参数注入路由,
    // 从而让整个应用都有路由功能
    const app = new Vue({
        el:'#app',
        router
    })
    // 现在,应用已经启动了!
</script>
</html>

路由的默认路径

如何可以让路径默认跳到到首页,并且<router-view>渲染首页组件呢?

const routes = [
    { path: '/', redirect:'/foo' },
    { path: '/foo', component: Foo },
    { path: '/bar', component: Bar }
]

模式

hash 模式

import { createRouter, createwebHashHistory } from 'vue-router'
import Foo from '../pages/Home.vue';

// 配置路由映射关系
const routes = [
    { path: '/', redirect:'/foo' },
    { path: '/foo', component: Foo },
]

const router = createRouter({
    routes,
    history: createwebHashHistory()
})

history 模式

import { createRouter, createwebHistory } from 'vue-router'
const router = createRouter({
    routes,
    history: createwebHistory()
})

router-link

router-link 事实上有很多属性可以配置

to 属性

是一个字符串,或者是一个对象,就和 router.push是等价的

replace 属性

设置 replace 属性的话,当点击时,会调用 router.replace()是等价的

active-class 属性

设置激活 a 元素后应用的 class,默认是 router-link-active

exact-active-class 属性

链接精准激活时,应用于渲染的 <a> 的 class,默认是 router-link-exact-active;

路由懒加载

当打包构建应用时,javascript 包会变得非常大,影响页面加载: 如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就会更加高效。

Vue Router 默认就支持动态来导入组件: component 可以传入一个组件,也可以接收一个函数,该函数 需要放回一个 Promise; 而 import 函数就是返回一个 Promise;

const routes = [
    { path: '/', redirect:'/foo' },
    { path: '/foo', component:()=>import('../pages/Home.vue') }
]

分模块 webpackChunkName

当构建的时候页面会产生一个 chunk值,你可以用webpackChunkName来命名让,打包后的文件,若是统一类型,可以打包在一起/分开,进行优化,可以提高首屏的渲染效率;

const routes = [
    { path: '/', redirect: '/foo' },
    { path: '/foo', component:()=>import(/* webpackChunkName: "Home" */'../pages/Home.vue') }
]