在 new Vue() 之后。 Vue 会调用 _init 函数进行初始化。它会初始化生命周期、事件、 props、 methods、 data、 computed 与 watch 等。
源码目录
src
-compiler // 编译相关(模板语法的解析)
-core // 核心代码(硬核都在这里)
-platforms // 跨平台支持(weex/web), 也是vue入口文件
-server // 服务端渲染
-sfc // .vue文件解析
-shared // 供其他目录使用的通用方法和好多好多常量
vue到底怎么来的
通过上一章节得知,vue的Runtime+Compiler入口文件为vue-2.6/src/platforms/web/entry-runtime-with-compiler.js。
那么vue到底是怎么来的呢?
打开vue的入口文件
这一步把./runtime/index导入的vue添加了些原型方法后导出
// 地址 vue-2.6/src/platforms/web/entry-runtime-with-compiler.js。
// 从./runtime/index 文件下引入vue 并向其添加些原型方法
import Vue from './runtime/index'
Vue.prototype.$mount = function (...) {}
Vue.compile = compileToFunctions
继续进入./runtime/index
这一步又把core/index导入的vue添加了些config等属性然后导出
// 地址 vue-2.6/src/platforms/web/runtime/index.js
import Vue from 'core/index'
Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isReservedAttr = isReservedAttr
Vue.config.getTagNamespace = getTagNamespace
Vue.config.isUnknownElement = isUnknownElement
// install platform runtime directives & components
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)
// install platform patch function
Vue.prototype.__patch__ = inBrowser ? patch : noop
...
export default Vue
再进入core/index
这一步继续把./instance/index导入的vue添加globalApi并导出
// 地址 vue-2.6/src/core/index
import Vue from './instance/index'
import { initGlobalAPI } from './global-api/index'
initGlobalAPI(Vue)
Vue.version = '__VERSION__'
export default Vue
进入./instance/index
这一步定义vue,并且声明了vue只能被new Vue 关键字创建。而且也通过些mixin函数向vue写入了各种属性
处理好后依然将vue导出了
// 地址 vue-2.6/core/instance/index.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
通过上面4个文件的代码得知,最初的vue是一个简单的对象。然后通过各个文件向它写入了的内容,让它变成了一个功能非常强大的对象。
分成4个文件,让代码结构非常清晰。这点是值得我们学习的