合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
目标: 1. 理解 Vue.use 插件机制 (Vue.use(VueRouter)) 2. VueRouter 实例分析 ## vue-router 工作原理 ![](https://img.kancloud.cn/b2/ca/b2cacecf4ef64dc658f83c9f84f07d22_1224x1553.png) ## Vue.use(xxx) 时干了什么 * 如果 xxx 是一个函数,那就执行 xxx 函数方法 * 如果 xxx 里有一个install属性,并且这个install 属性也是一个函数,那么就执行这个函数,不执行xxx ``` function a() { console.log('aaa') } // a.install = function() { // console.log('bbb') // } a.install = function(_vue) { console.log(_vue) } Vue.use(a) ``` * install 函数的第一个参数是 vue 的构造函数 ( Vue.use(VueRouter) 执行时,传入了vue的构造函数,所以install可以取到) ![](https://img.kancloud.cn/00/9e/009e7ffbe24cc3b806cd440d2c20cedc_1755x591.png) ## 手写 VueRouter 实例 ``` let Vue class VueRouter { constructor(options) { Vue.util.defineReactive(this, 'current', '/') this.current = '/' this.routes = options.routes this.init() } init() { window.addEventListener('hashchange', () \=> { this.current = location.hash.slice(1) }) } } VueRouter.install = function(_vue) { Vue = _vue Vue.mixin({ beforeCreate() { if(this.$options.router){ Vue.prototype.$router = this.$options.router } } }) Vue.component('router-link', { props: { to: { type: String, default: '' } }, render(h){ return h('a', { attrs: { href: `#${this.to}` } }, this.$slots.default) } }) Vue.component('router-view', { render(h) { // 需要渲染的是一个组件 // 1: 要知道当前渲染的是哪一个路径 console.log(this.$router, 'this.$router') const c = this.$router.current const currentRoutes = this.$router.routes.find(item => item.path === c) console.log(currentRoutes, 'currentRoutes') return h(currentRoutes.component) } }) } export default VueRouter ```