开启源码之旅
修改package.json,找到scripts,在dev中添加--sourcemap
"scripts":{
"dev": "rollup -w -c scripts/config.js --sourcemap --environment TARGET:web-full-dev",
}
然后npm run dev运行,在控制台现在会显示
在根目录下面的examples的文件夹中新建test.html,并写入
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../dist/vue.js"></script>
</head>
<body>
<div id="app">
</div>
</body>
</html>
<script>
const app = new Vue({
})
</script>
经过上述操作以后,就可以开始去调试源码了
vue初始化
我们首先找到定义vue的文件位置src\core\instance\index.js,来看看当我们引入vue.js时,js文件中都发生些什么事。
import { initMixin } from './init'
import { stateMixin } from './state'
import { renderMixin } from './render'
import { eventsMixin } from './events'
import { lifecycleMixin } from './lifecycle'
import { warn } from '../util/index'
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)
export default Vue
在我们引入vue.js时,会按顺序执行下面的方法,initMixin主要用于定义this._init方法,我们先从stateMixin方法开始看起
stateMixin
从源码中可以看出,stateMixin主要定义了$data,$props,$set,$delete,$watch,同时可以看到$data,$props是只读属性。
eventsMixin
eventsMixin主要定义了$on,$once,$off,$emit
lifecycleMixin
lifecycleMixin主要定义了_update,$forceUpdate,$destroy
renderMixin
renderMixin主要定义$nextTick,_render,同时在其中有个installRenderHelpers的方法,这个方法主要是用来定义一些程序内部使用的api方法
export function installRenderHelpers (target: any) {
target._o = markOnce
target._n = toNumber
target._s = toString
target._l = renderList
target._t = renderSlot
target._q = looseEqual
target._i = looseIndexOf
target._m = renderStatic
target._f = resolveFilter
target._k = checkKeyCodes
target._b = bindObjectProps
target._v = createTextVNode
target._e = createEmptyVNode
target._u = resolveScopedSlots
target._g = bindObjectListeners
target._d = bindDynamicKeys
target._p = prependModifier
}
因此vue的定义文件中,主要声明Vue,定义了Vue原型上的一些方法,这些api,在后面我们再进行详细分析,并且看看,我们再new Vue()时,都发什么些啥