zcqiand

前言

学习vue-router就要先了解路由是什么?前端路由的实现原理?vue-router如何使用?等等这些问题,就是本篇要探讨的主要问题。

vue-router是什么

路由是什么?

大概有两种说法:从路由的用途上来解释路由就是指随着浏览器地址栏的变化,展示给用户的页面也不相同。从路由的实现原理上来解释路由就是URL到函数的映射。

vue-router是什么

Vue Router 是 Vue.js 官方的路由管理器,它和 Vue.js 的核心深度集成。

vue-router实现原理

基于hash

基于location.hash来实现的。其实现原理也很简单,location.hash的值就是URL中#后面的内容。比如下面这个网站,它的location.hash='#me':

https://localhost#me

hash也存在下面几个特性:

  • URL中hash值只是客户端的一种状态,也就是说当向服务器端发出请求时,hash部分不会被发送。
  • hash值的改变,都会在浏览器的访问历史中增加一个记录。因此我们能通过浏览器的回退、前进按钮控制hash的切换。
  • 我们可以使用hashchange事件来监听hash的变化。

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

基于History

如果不想要很丑的 hash,我们可以用路由的 history 模式,只需要在配置路由规则时,加入"mode: 'history'",这种模式充分利用 history.pushState API 来完成 URL 跳转而无须重新加载页面。其中做最主要的API有以下两个:history.pushState()和history.repalceState()。

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

如何使用vue-router

效果

使用

首先,安装vue-router

npm install vue-router

接下来,在main.js定义 (路由) 组件、安装插件、定义路由、创建 router 实例,然后传 routes 配置、创建和挂载根实例。

import Vue from 'vue'
import VueRouter from 'vue-router';
import App from './App.vue'
import './plugins/element.js'

// 1. 定义 (路由) 组件。
import TodoList from './components/TodoList.vue';
import TodoListWithUI from './components/TodoListWithUI.vue'
import TodoListWithApi from './components/TodoListWithApi.vue'

Vue.config.productionTip = false

// 2. 安装插件
Vue.use(VueRouter); 

// 3. 定义路由
// 每个路由应该映射一个组件。 其中"component" 可以是
// 通过 Vue.extend() 创建的组件构造器,或者,只是一个组件配置对象。
const routes = [
  { path: '/noui', component: TodoList },
  { path: '/ui', component: TodoListWithUI },
  { path: '/api', component: TodoListWithApi }
]

// 4. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new VueRouter({
  routes // (缩写) 相当于 routes: routes
})

// 5. 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由,
// 从而让整个应用都有路由功能
new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

最后,App.vue使用 router-link 组件来导航,和放置路由出口 router-view

<template>
<div id="app">
    <p>
        <!-- 使用 router-link 组件来导航. -->
        <!-- 通过传入 `to` 属性指定链接. -->
        <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
        <router-link to="/noui">无UI</router-link>&nbsp;&nbsp;
        <router-link to="/ui">有UI</router-link>&nbsp;&nbsp;
        <router-link to="/api">有API</router-link>&nbsp;&nbsp;
    </p>
    <!-- 路由出口 -->
    <!-- 路由匹配到的组件将渲染在这里 -->
    <router-view></router-view>
</div>
</template>

<script>
export default {
    name: 'app',
    components: {}
}
</script>

小结

目前为止,我们完成了vue-router的基本用法,是不是还是挺简单的呀。其他动态路由匹配、嵌套路由等用法我们在这里不进行展开了。

文中用到的代码我们放在:https://github.com/zcqiand/miscellaneous/tree/master/vue

相关文章: