咱们常常经过这样的方法建立一个Vue实例,定义该组件相关的dom结构(el),数据(data),方法(methods),组件(component)等等:javascript
var vm = new Vue({ el: '#example', data: { newTodoText: '', visitCount: 0, hideCompletedTodos: false, todos: [], }, methods:{ clickHandler:function(){ console.log('你被点了!'); } } created: function () { console.log('test'); } });
咱们经常知其然,而不知其因此然。今天咱们就来看看Vue的源码是怎么样子的。如下是Vue的构造函数,主要是经过_init()方法将用户定义的组件信息进行初始化。java
function Vue (options) { if ("development" !== 'production' && !(this instanceof Vue) ) { warn('Vue is a constructor and should be called with the `new` keyword'); } this._init(options); } initMixin(Vue); //初始化入口 stateMixin(Vue);//数据绑定 eventsMixin(Vue);//事件方法初始化 lifecycleMixin(Vue);//生命周期方法初始化 renderMixin(Vue);
initMixin(Vue)是Vue初始化的入口,主要经过调用_init()方法进行初始化,具体逻辑以下:
stateMixin(Vue)使用Object.defineProperty程序化的构建data和props对象,给她们添加了 get和set方法。同时暴露了$set,$delete,$watch三个方法。$watch就是观察一个值的变化, 相似原生js里onChange。
eventsMixin(Vue)定义了$on,$once,$off,$emit四个方法。$emit用于触发自定义事件。 lifecycleMixin(Vue)定义了_update,$forceUpdate,$destroy三个方法。 renderMixin(Vue)渲染方法,用来生成render函数和vnode。