intro
Vue.js 一个核心思想是数据驱动。所谓数据驱动,是指视图是由数据驱动生成的,我们对视图的修改,不会直接操作 DOM,而是通过修改数据。
本文将介绍vue如何将模板和数据渲染成最终的 DOM。
实例
html
<div id="app">
{
{ message }}
</div>
JavaScript
var app = new Vue({
el: '#app',
data: {
message: 'Hello world!'
}
})
最终展现是
Hello world
new Vue()
入口:src/core/instance/index.js
function Vue (options) {
if (process.env.NODE_ENV !== '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)
可以看到new的过程调用了_init初始化操作。后边initMixin等函数是在vue的prototype上绑定了若干方法。这里使用es5的类写法,而非es6,这样的好处就是下边分类的Mixin方法可以灵活的在prototype上挂载分类的方法。
_init方法
Vue.prototype._init = function (options?: Object) {
const vm: Component = this
// a uid
vm._uid = uid++
let startTag, endTag
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
startTag = `vue-perf-start:${
vm._uid}`
endTag = `vue-perf-end:${
vm._uid}`
mark(startTag)
}
// a flag to avoid this