-
Notifications
You must be signed in to change notification settings - Fork 8
/
lifecycle3.js
110 lines (92 loc) · 2.26 KB
/
lifecycle3.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
var instance = null;
function Vue(options) {
instance = this;
this.$options = options;
this._data = typeof options.setup === 'function' ? options.setup() : {};
this._proxyData();
this.$mount(options.el);
}
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;
}
});
});
};
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.render = function() {
if (typeof this.$options.render === 'function') {
this.$el.innerHTML = this.$options.render.call(this._data);
}
};
function onBeforeUnmount(callback) {
instance.$options.beforeMount = callback;
}
function onMounted(callback) {
instance.$options.mounted = callback;
}
function onBeforeUpdate(callback) {
instance.$options.beforeUpdate = callback;
}
function onUpdated(callback) {
instance.$options.updated = callback;
}
function reactive(obj) {
return new Proxy(obj, {
get(target, key) {
return target[key];
},
set(target, key, value) {
target[key] = value;
if (typeof instance.$options.beforeUpdate === 'function') {
instance.$options.beforeUpdate.call(instance);
}
instance.render();
if (typeof instance.$options.updated === 'function') {
instance.$options.updated.call(instance);
}
}
});
}
// 使用示例
var app = new Vue({
el: '#app',
setup: function() {
const state = reactive({
message: 'Hello, Vue!'
});
onBeforeUnmount(function() {
console.log('beforeMount hook');
});
onMounted(function() {
console.log('mounted hook');
});
onBeforeUpdate(function() {
console.log('beforeUpdate hook');
});
onUpdated(function() {
console.log('updated hook');
});
return {
state
}
},
render: function() {
return '<p>' + this.state.message + '</p>';
}
});