-
Notifications
You must be signed in to change notification settings - Fork 8
/
slot.js
87 lines (77 loc) · 2.09 KB
/
slot.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;
this._data = typeof options.data === 'function' ? options.data() : options.data;
this._components = options.components || {};
this._proxyData();
this._compileTemplate();
this._proxyComponents();
}
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._compileTemplate = function() {
var self = this;
var el = this.$options.el
var template = this.$options.template || '';
var evalExpression = function(expression) {
with (self) return eval(expression);
}
var compiledTemplate = template.replace(/\{\{(.*?)\}\}/g, function(match, expression) {
var value = evalExpression(expression);
return value !== undefined ? value : '';
});
var element = el ? document.querySelector(el) : document.createElement('div');
element.innerHTML = compiledTemplate.trim();
this.$el = el ? element : element.childNodes[0];
};
Vue.prototype._proxyComponents = function() {
var self = this;
var components = this._components;
Object.keys(components).forEach(function(componentName) {
var component = new Vue(components[componentName]);
self.$el.querySelectorAll(componentName).forEach(function(element) {
component.$el.querySelectorAll('slot').forEach(function(slot) {
slot.innerHTML = element.innerHTML;
});
element.innerHTML = component.$el.outerHTML;
});
});
};
// 使用示例
var HelloComponent = {
data: function() {
return {
name: 'John'
};
},
template: `
<div>
<h1>{{ name }}</h1>
<slot></slot>
</div>
`
};
var app = new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
},
components: {
HelloComponent
},
template: `
<HelloComponent>
<p>{{ message }}</p>
</HelloComponent>
`
});