vue-router原理及源码实现

264 阅读1分钟

一般我们使用vue-router的步骤如下:

1、先引入路由插件(router.js)

import VueRouter from 'vue-router'

2、注册插件(router.js)

Vue.use()方法其实是内部执行了一个install方法,后面会详细说明。

Vue.use(VueRouter)

3、实现路由实例(router.js)

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    {
        path: '/about',
        name: 'About',
        component: About
    }
]
const router = new VueRouter({
    routes
})

4、在跟组件上添加该实例(main.js)

import router from './router';
new Vue({
    router,
}).$mount("#app");

谈谈路由的作用是什么?

在单页面应用程序中路由的作用是:

  1. 改变url地址发面发生跳转;
  2. 显示url对应的视图内容,但页面不刷新。

实现过程

  1. 需求分析:
    1. url发生改变,但是页面不刷新
      • 使用哈希路由 hash #/about
      • 使用H5提供的History api /about
    2. 根据url显示对应的内容
      • 实现router-view(是一个占位符,里面包含视图的内容)
      • 实现数据响应式
  2. 代码实现:
    index.js
import Vue from "vue";
import VueRouter from "./hvue-router";
import Home from "../views/Home.vue";
import About from "../views/About.vue";

Vue.use(VueRouter);
const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    {
        path: '/about',
        name: 'About',
        component: About
    }
]
const router = new VueRouter({
    routes
})
export default router; 

hvue-router.js

let Vue;
class VueRouter {
    constructor(options) {
        this.$options = options;
        //给当前对象指定一个响应式属性,目的是路径发生变化,数据也跟着变化
        Vue.util.defineReactive(this, "current", window.location.hash.slice(1))
        //监听路径改变,当前current也改变
        window.addEventListener("hashchange", () => {
            this.current = window.location.hash.slice(1);
        })
    }
}

VueRouter.install = function (_Vue) {
    //传入构造函数之后就可以定义期进行扩展
    Vue = _Vue;
    //使用混入方式,将自定义的属性或方法挂载到Vue实例上
    Vue.mixin({
        beforeCreate() {
            //当router实例和Vue实例全部创建完毕之后,
            //将当前的路由表中的路由选项扩展到Vue的扩展属性$router上面
            if (this.$options.router) {
                Vue.prototype.$router = this.$options.router;
            }
        }
    })
    Vue.component("router-link", {
        props: {
            to: {
                type: String,
                required: true
            }
        },
        render(h) {
            return h(
                "a",
                {
                    attrs: {
                        href: "#" + this.to
                    }
                },
                this.$slots.default
            );
        }
    });
    // h 是render函数调用时,框架传入的createElement,等同于react中的createElement,返回vdom
    Vue.component("router-view", {
        render(h) {
            let component = null;
            const routes = this.$router.$options.routes;
            const route = routes.find((route) => route.path === this.$router.current);
            if (route) {
                component = route.component;
            }
            return h(component);
        }
    });
}
export default VueRouter;

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './hvue-router'
new Vue({
    router,
    render: h => h(App)
}).$mount('#app')

app.vue

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <router-view />
  </div>
</template>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;
}

#nav a {
  font-weight: bold;
  color: #2c3e50;
}

#nav a.router-link-exact-active {
  color: #42b983;
}
</style>

运行效果:

路由运行结果1.png

路由运行结果2.png