function EventBus() {
this._events = {};
}
EventBus.prototype.on = function(eventName, callback) {
if (!this._events[eventName]) {
this._events[eventName] = [];
}
this._events[eventName].push(callback);
};
EventBus.prototype.emit = function(eventName, payload) {
if (this._events[eventName]) {
this._events[eventName].forEach(function(callback) {
callback(payload);
});
}
};
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._eventBus = new EventBus();
this._proxyData();
this._proxyMethods();
this._createComputed();
this._createWatchers();
if (typeof options.created === 'function') {
options.created.call(this);
}
this.$mount();
}
Vue.prototype.$render = function() {
if (typeof this.$options.render === 'function' && this.$options.el) {
this.$el = document.querySelector(this.$options.el);
this.$el.innerHTML = this.$options.render.call(this);
} else {
this._compileTemplate();
this._proxyComponents();
}
};
Vue.prototype.$mount = function() {
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(t
两百行代码实现简易版本的vue框架
于 2023-06-26 15:01:24 首次发布