|
| 1 | +// 我们的自己的插件 |
| 2 | +// 实现⼀个插件 |
| 3 | +// 实现VueRouter类 |
| 4 | +// 处理路由选项 |
| 5 | +// 监控url变化,hashchange |
| 6 | +// 响应这个变化 |
| 7 | +// 实现install⽅法 |
| 8 | + |
| 9 | +let Vue; |
| 10 | + |
| 11 | +// new VueRouter({routes}) |
| 12 | +class KVueRouter { |
| 13 | + constructor(options) { |
| 14 | + this.$options = options; |
| 15 | + |
| 16 | + // current必须是响应式的 |
| 17 | + // 如何做到? |
| 18 | + // set只能在响应式对象上动态添加新属性 |
| 19 | + // new Vue({data() { |
| 20 | + // return { |
| 21 | + // key: value |
| 22 | + // } |
| 23 | + // },}) |
| 24 | + Vue.util.defineReactive( |
| 25 | + this, |
| 26 | + "current", |
| 27 | + window.location.hash.slice(1) || "/" |
| 28 | + ); |
| 29 | + // this.current = window.location.hash.slice(1) || '/' |
| 30 | + // 监控hashchange |
| 31 | + window.addEventListener("hashchange", () => { |
| 32 | + console.log(this.current); |
| 33 | + this.current = window.location.hash.slice(1); |
| 34 | + }); |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +// vue插件:需要实现一个静态方法install |
| 39 | +// install(Vue, ...) |
| 40 | +KVueRouter.install = function(_Vue) { |
| 41 | + Vue = _Vue; |
| 42 | + |
| 43 | + // console.log(this); |
| 44 | + // $router注册 |
| 45 | + // 延迟执行注册代码 |
| 46 | + // 混入:Vue.mixin({beforeCreate(){}}) |
| 47 | + Vue.mixin({ |
| 48 | + beforeCreate() { |
| 49 | + // console.log(this); // this是组件实例 |
| 50 | + // 如果当前this是根组件,它选项中必有一个router |
| 51 | + if (this.$options.router) { |
| 52 | + Vue.prototype.$router = this.$options.router; |
| 53 | + } |
| 54 | + }, |
| 55 | + }); |
| 56 | + |
| 57 | + // 两个全局组件: router-link、router-view |
| 58 | + Vue.component("router-link", { |
| 59 | + props: { |
| 60 | + to: { |
| 61 | + type: String, |
| 62 | + required: true, |
| 63 | + }, |
| 64 | + }, |
| 65 | + render(h) { |
| 66 | + // <router-link to="/about">xxx</router-link> |
| 67 | + // <a href="#/about">xxx</a> |
| 68 | + // return <a href={"#" + this.to}>{this.$slots.default}</a> |
| 69 | + return h("a", { attrs: { href: "#" + this.to } }, this.$slots.default); |
| 70 | + }, |
| 71 | + }); |
| 72 | + Vue.component("router-view", { |
| 73 | + // render什么时候会执行? |
| 74 | + // init执行一次 |
| 75 | + // 未来响应式数据变化会再次执行 |
| 76 | + render(h) { |
| 77 | + // 1.获取hash部分#/about |
| 78 | + // this.$router.$options.routes |
| 79 | + // 2.根据上面地址获取对应组件配置About |
| 80 | + // 3.h(About) |
| 81 | + console.log(this.$router.$options); |
| 82 | + console.log(this.$router.current); |
| 83 | + let component = null; |
| 84 | + const route = this.$router.$options.routes.find( |
| 85 | + (route) => route.path === this.$router.current |
| 86 | + ); |
| 87 | + if (route) { |
| 88 | + component = route.component; |
| 89 | + } |
| 90 | + return h(component); |
| 91 | + }, |
| 92 | + }); |
| 93 | +}; |
| 94 | + |
| 95 | +export default KVueRouter; |
0 commit comments