第三章 Vue.js 框架源码与进阶
模块一 手写 Vue Router、手写响应式实现、虚拟 DOM 和 Diff 算法
手写 Vue Router
实现一个简单的 vue-router history 模式 和 hash模式
// 通过 Vue.use(VueRouter) 调用,Vue.use会去调用插件的静态方法 install,并传入当前vue的实例
let _Vue = null;
export default class VueRouter {
static install(Vue) {
// 判断插件是否已经被安装,通过在静态属性上挂载一个布尔值来判断
if (VueRouter.install.installed) {
return;
}
VueRouter.install.installed = true;
// 把Vue构造函数记录到全局变量
_Vue = Vue;
// 将创建Vue实例时传入的router配置对象注入到Vue实例上,使用mixin混入
_Vue.mixin({
beforeCreate() {
// 仅在vue实例下执行,组件内部不执行,组件内部没有$options.router
if (this.$options.router) {
_Vue.prototype.$router = this.$options.router;
this.$options.router.init();
}
},
});
}
constructor(options) {
// 构造基础属性,data是响应式的,储存基础路由 '/'
this.options = options;
this.routeMap = {};
this.data = _Vue.observable({
current: "/",
});
this.mode = options.mode || "hash";
}
init() {
this.createRouterMap();
this.initComponents(_Vue);
this.initEvent();
}
createRouterMap() {
// 将路由规则解析成键值对,储存在routeMap上
this.options.routes.forEach((route) => {
this.routeMap[route.path] = route.component;
});
}
// 创建 router-link,router-view 组件
initComponents(Vue) {
Vue.component("router-link", {
props: {
to: String,
},
// 运行时版本不能使用template模板,改用render函数
// template: '<a :href="to"><slot></slot></a>'
render(h) {
return h(
"a",
{
attrs: {
href: this.to,
},
on: {
click: this.clickHandler, // 取消a标签点击的默认跳转
},
},
[this.$slots.default] // 默认插槽找到组件标签中的内容
);
},
methods: {
clickHandler(e) {
e.preventDefault();
// 修改路由
if(this.mode === 'hash'){
window.location.hash = this.to;
} else {
history.pushState({}, "", this.to);
}
this.$router.data.current = this.to;
},
},
});
const self = this;
Vue.component("router-view", {
render(h) {
// 获取路由对应的组件渲染
const component = self.routeMap[self.data.current];
return h(component);
},
});
}
initEvent() {
if (this.mode === "hash") {
window.addEventListener("hashchange", () => {
this.data.current = window.location.hash.slice(1);
});
} else {
// 历史记录变更时触发路由变化
window.addEventListener("popstate", () => {
this.data.current = window.location.pathname;
});
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106