版权声明:感谢您的浏览,引用请标明出处. https://blog.csdn.net/qq_16756237/article/details/82193598
基于js的vue总让给我感觉很神秘,到底在交互的时候vue利用js对template和component做了什么,带着这些问题,花了一天时间试读了一下源码,当然只是熟悉其框架和其响应式原理,了解个大概,总结如下
入口文件到核心文件 core/instance/index.js
- 在GitHub上克隆下源码,npm把核心vue编译出来:
$ npm install
$ npm run dev
- run 的是package.json中的dev,在dev中:
"dev":"rollup -w -c scripts/config.js --environment TARGET:web-full-dev"
//rollup为打包工具,在install之前需下载
注意上面指令中的两个关键词scripts/config.js和web-full-dev,接下来让看看script/config.js这个文件。
- 注意到config.js代码最后:
if (process.env.TARGET) {
module.exports = genConfig(process.env.TARGET)
} else {
exports.getBuild = genConfig
exports.getAllBuilds = () => Object.keys(builds).map(genConfig)
}
这里TARGET是我们在run时候的参数,我们传入的TARGET是web-full-dev,那么带入到方法中,最终会看到这样一个object:
'web-full-dev': {
// 入口文件
entry: resolve('web/entry-runtime-with-compiler.js'),
// 输出文件
dest: resolve('dist/vue.js'),
// 格式
format: 'umd',
// 环境
env: 'development',
// 别名
alias: { he: './entity-decoder' },
banner
},
看不懂,也不知道是干啥的,且通过翻译猜想一下.
- 看到入口文件到了web/entry-runtime-with-compiler.js文件下(藏在platforms/web里面),才终于看到了熟悉的语法和字眼import vue:
import Vue from './runtime/index'
追踪引入的文件路径,点进去
import Vue from 'core/index'
其中又引入
import Vue from './instance/index'
- 打开instance/index后,终于找到了Vue的定义地方。
可以在这里实例一个HTML,引入vue,在控制台查看vue的所有属性和方法(在控制台console.dir(Vue));
挂在在vue上的属性
- 在一开始寻找Vue核心文件的过程中,从entry→tuntime→core→instance→index.js,其实每层嵌套都是对vue属性Prototype的丰富,说白就是挂载方法.
instance(位于src/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
在引入的路径找到这些个方法做了什么
initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)
- initMixin(src/core/instance/init.js)
Vue.prototype._init = function (options?: Object) {}
复制代码在传入的Vue对象的原型上挂载了_init方法。
- stateMixin(src/core/instance/state.js)
// Object.defineProperty(Vue.prototype, '$data', dataDef)
// 这里$data只提供了get方法,set方法再非生产环境时会给予警告
Vue.prototype.$data = undefined;
// Object.defineProperty(Vue.prototype, '$props', propsDef)
// 这里$props只提供了get方法,set方法再非生产环境时会给予警告
Vue.prototype.$props = undefined;
Vue.prototype.$set = set
Vue.prototype.$delete = del
Vue.prototype.$watch = function() {}
- eventsMixin(src/core/instance/events.js)
Vue.prototype.$on = function() {}
Vue.prototype.$once = function() {}
Vue.prototype.$off = function() {}
Vue.prototype.$emit = function() {}
- lifecycleMixin(src/core/instance/lifecycle.js)
Vue.prototype._update = function() {}
Vue.prototype.$forceUpdate = function () {}
Vue.prototype.$destroy = function () {}
- renderMixin(src/core/instance/render.js)
// installRenderHelpers
Vue.prototype._o = markOnce
Vue.prototype._n = toNumber
Vue.prototype._s = toString
Vue.prototype._l = renderList
Vue.prototype._t = renderSlot
Vue.prototype._q = looseEqual
Vue.prototype._i = looseIndexOf
Vue.prototype._m = renderStatic
Vue.prototype._f = resolveFilter
Vue.prototype._k = checkKeyCodes
Vue.prototype._b = bindObjectProps
Vue.prototype._v = createTextVNode
Vue.prototype._e = createEmptyVNode
Vue.prototype._u = resolveScopedSlots
Vue.prototype._g = bindObjectListeners
//
Vue.prototype.$nextTick = function() {}
Vue.prototype._render = function() {}
很直白,这五个方法都是直接给vue的prototype直接挂在方法.(具体方法怎么实现无外乎js封装起来的)
Core(位于src/core/index.js)
import Vue from './instance/index'
import { initGlobalAPI } from './global-api/index'
import { isServerRendering } from 'core/util/env'
import {
FunctionalRenderContext
} from 'core/vdom/create-functional-component'
// 初始化全局API
initGlobalAPI(Vue)
Object.defineProperty(Vue.prototype, '$isServer', {
get: isServerRendering
})
Object.defineProperty(Vue.prototype, '$ssrContext', {
get () {
/* istanbul ignore next */
return this.$vnode && this.$vnode.ssrContext
}
})
// expose FunctionalRenderContext for ssr runtime helper installation
Object.defineProperty(Vue, 'FunctionalRenderContext', {
value: FunctionalRenderContext
})
Vue.version = '__VERSION__'
export default Vue
- 复制代码按照代码执行顺序,我们看看initGlobalAPI(Vue)方法内容:
// Object.defineProperty(Vue, 'config', configDef)
Vue.config = { devtools: true, …}
Vue.util = {
warn,
extend,
mergeOptions,
defineReactive,
}
Vue.set = set
Vue.delete = delete
Vue.nextTick = nextTick
Vue.options = {
components: {},
directives: {},
filters: {},
_base: Vue,
}
// extend(Vue.options.components, builtInComponents)
Vue.options.components.KeepAlive = { name: 'keep-alive' …}
// initUse
Vue.use = function() {}
// initMixin
Vue.mixin = function() {}
// initExtend
Vue.cid = 0
Vue.extend = function() {}
// initAssetRegisters
Vue.component = function() {}
Vue.directive = function() {}
Vue.filter = function() {}
- 不难看出又是对vue属性的添加
runtime(位于src/platforms/web/runtime/index.js)
- 这里首先针对web,对Vue.config来了一小波方法添加。
Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isReservedAttr = isReservedAttr
Vue.config.getTagNamespace = getTagNamespace
Vue.config.isUnknownElement = isUnknownElement
- 向options中directives增加了model以及show指令:
// extend(Vue.options.directives, platformDirectives)
Vue.options.directives = {
model: { componentUpdated: ƒ …}
show: { bind: ƒ, update: ƒ, unbind: ƒ }
}
- 向options中components增加了Transition以及TransitionGroup:
// extend(Vue.options.components, platformComponents)
Vue.options.components = {
KeepAlive: { name: "keep-alive" …}
Transition: {name: "transition", props: {…} …}
TransitionGroup: {props: {…}, beforeMount: ƒ, …}
}
- 在原型中追加patch以及$mount:
// 虚拟dom所用到的方法
Vue.prototype.__patch__ = patch
Vue.prototype.$mount = function() {}
- 以及对devtools的支持。
entry(src/platforms/web/entry-runtime-with-compiler.js)
在entry中,覆盖了$mount方法。
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component{...}
挂载compile,compileToFunctions方法是将template编译为render函数
Vue.compile = compileToFunctions
小结
至此,我们完整的过了一遍在web中Vue的构造函数的变化过程:
- 通过instance对Vue.prototype进行属性和方法的挂载。
- 通过core对Vue进行静态属性和方法的挂载。
- 通过runtime添加了对platform === ‘web’的情况下,特有的配置、组件、指令。
- 通过entry来为$mount方法增加编译template的能力。