-
Notifications
You must be signed in to change notification settings - Fork 8
/
lifecycle.js
87 lines (75 loc) · 1.99 KB
/
lifecycle.js
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
function Vue(options) {
this.$options = options;
if (typeof options.beforeCreate === 'function') {
options.beforeCreate.call(this);
}
this._data = typeof options.data === 'function' ? options.data() : options.data;
this._proxyData();
if (typeof options.created === 'function') {
options.created.call(this);
}
this.$mount(options.el);
}
Vue.prototype.$mount = function(el) {
this.$el = document.querySelector(el);
if (typeof this.$options.beforeMount === 'function') {
this.$options.beforeMount.call(this);
}
this.render();
if (typeof this.$options.mounted === 'function') {
this.$options.mounted.call(this);
}
};
Vue.prototype._proxyData = function() {
var self = this;
Object.keys(this._data).forEach(function(key) {
Object.defineProperty(self, key, {
get: function() {
return self._data[key];
},
set: function(newValue) {
self._data[key] = newValue;
if (typeof self.$options.beforeUpdate === 'function') {
self.$options.beforeUpdate.call(self);
}
self.render();
if (typeof self.$options.updated === 'function') {
self.$options.updated.call(self);
}
}
});
});
};
Vue.prototype.render = function() {
if (typeof this.$options.render === 'function') {
this.$el.innerHTML = this.$options.render.call(this);
}
};
// 使用示例
var app = new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
},
beforeCreate: function() {
console.log('beforeCreate hook');
},
created: function() {
console.log('created hook');
},
beforeMount: function() {
console.log('beforeMount hook');
},
mounted: function() {
console.log('mounted hook');
},
beforeUpdate: function() {
console.log('beforeUpdate hook');
},
updated: function() {
console.log('updated hook');
},
render: function() {
return '<p>' + this.message + '</p>';
}
});