vue在实例挂在前做了哪些事情 初始化 建立更新机制
dearweb
发布:2022-06-10 08:39:06阅读:
Vue中有一个独特的编译器模块“compiler”,它的主要作用是将用户编写的template编译为js中可执行的render函数,之所以需要这个编译过程,是为了便于前端程序员能高效的编写视图模板,相对而言,我们还是更愿意用HTML来编写视图,直观且高效,手写render函数不仅效率低下,而且失去了编译器的优化能力。
在vue中编译器对template 进行解析,这一步成为parse,结束之后会得到一个JS对象,我们成为抽象语法树AST,然后是对AST进行深加工的转换过程,这一步称为 transform , 最后将前面得到的AST生成为JS代码,也就是render函数,说了这么多,下面我们一起来看看这个过程吧。
以 Runtime + Compiler 版的 vue.js 为例,所以入口文件为src/platforms/web/entry-runtime-with-compiler.js
src/platforms/web/entry-runtime-with-compiler.js文件解析
// src/platforms/web/entry-runtime-with-compiler.js
import Vue from './runtime/index'
import { query } from './util/index'
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && query(el) //内部判断el是否是字符串,不是的话就直接返回
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
process.env.NODE_ENV !== 'production' && warn(
`Do not mount Vue to <html> or <body> - mount to normal elements instead.`
)
return this
}
const options = this.$options
// resolve template/el and convert to render function
if (!options.render) {
let template = options.template
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template)
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !template) {
warn(
`Template element not found or is empty: ${options.template}`,
this
)
}
}
} else if (template.nodeType) {
template = template.innerHTML
} else {
if (process.env.NODE_ENV !== 'production') {
warn('invalid template option:' + template, this)
}
return this
}
} else if (el) {
template = getOuterHTML(el)
}
if (template) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile')
}
const { render, staticRenderFns } = compileToFunctions(template, {
outputSourceRange: process.env.NODE_ENV !== 'production',
shouldDecodeNewlines,
shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this)
options.render = render
options.staticRenderFns = staticRenderFns
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile end')
measure(`vue ${this._name} compile`, 'compile', 'compile end')
}
}
}
return mount.call(this, el, hydrating)
}
function getOuterHTML (el: Element): string {
if (el.outerHTML) {
return el.outerHTML
} else {
const container = document.createElement('div')
container.appendChild(el.cloneNode(true))
return container.innerHTML
}
}(1)先获得 Vue 原型上的$mount方法,用变量mount进行缓存,然后再重新定义$mount。 Vue 原型上的$mount方法是在src/platforms/web/runtime/index.js文件下定义的。
问:为什么在src/platforms/web/runtime/index.js文件下定义的$mount方法要在src/platforms/web/entry-runtime-with-compiler.js文件重新定义一遍?
答:因为 Runtime Only 版本不需要 Runtime + Compiler 版本的逻辑。src/core/instance/init.js下的vm.$mount(vm.$options.el)中的$mount调用的是src/platforms/web/entry-runtime-with-compiler.js的$mount函数。
(2)重新定义的Vue.prototype.$mount函数的实现:
1)先对传入的el参数进行处理,它可以是给字符串也可以是Element,然后调用了query方法,query方法在src/platforms/web/util/index.js文件中有定义。
在src/platforms/web/util/index.js文件中,如果el是字符串,则调用原生 API ——document.querySelector()方法,如果找不到el会报错并返回空的div,找到的话直接返回document.querySelector(el);如果el不是字符串,已经是个 DOM 对象则直接返回el。
<!--document.querySelector()方法:
console.log(document.querySelector("#app"))-->
<div id="app">Hello Vue!</div>
// src/platforms/web/util/index.js
export function query (el: string | Element): Element {
if (typeof el === 'string') {
const selected = document.querySelector(el)
if (!selected) {
process.env.NODE_ENV !== 'production' && warn(
'Cannot find element: ' + el
)
return document.createElement('div')
}
return selected
} else {
return el
}
}2)el = el && query(el)的el就被转换成一个 DOM 对象。然后对el进行判断,如果el是body或documentElement(文档标签),会进行报错,意思是 Vue 是不能直接挂载到html或body上,因为挂载会把整个body覆盖,整个 HTML 文档会发生错误。所以我们通常都是<div id="app"></div>方式去实现而不是直接挂载在 body 下。
var a = '#app',b = document.querySelector("#app");
var c = a && b,d = b && a;
console.log(c); // <div id="app">Hello Vue!</div>
console.log(d); // #app3)拿到$options,判断有没有定义render方法,然后判断有没有写template,如果template是字符串类型则对template进行处理,如果template是一个 DOM 对象的话,就拿template的innerHTML,如果template不是以上两种类型就会有警告;没有template就会拿到el并调用getOuterHTML方法。
getOuterHTML方法拿到el的outerHTML,如果有就直接返回,否则在el.outerHTML外包一层div,再执行innerHTML,返回字符串。然后就是编译过程了。此时template是"<div id="app">{{ message }}</div>"(字符串类型)
4)如果有render函数直接调用mount方法,这个mount方法是之前缓存的$mount,因此又回到了src/platforms/web/runtime/index.js文件中,在该文件中调用mountComponent方法。mountComponent方法来自src/core/instance/lifecycle.js文件。
// src/core/instance/lifecycle.js
export function mountComponent (
vm: Component,
el: ?Element,
hydrating?: boolean
): Component {
vm.$el = el
if (!vm.$options.render) {
vm.$options.render = createEmptyVNode
if (process.env.NODE_ENV !== 'production') {
/* istanbul ignore if */
if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
vm.$options.el || el) {
warn(
'You are using the runtime-only build of Vue where the template ' +
'compiler is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
)
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
)
}
}
}
callHook(vm, 'beforeMount')
let updateComponent
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
updateComponent = () => {
const name = vm._name
const id = vm._uid
const startTag = `vue-perf-start:${id}`
const endTag = `vue-perf-end:${id}`
mark(startTag)
const vnode = vm._render()
mark(endTag)
measure(`vue ${name} render`, startTag, endTag)
mark(startTag)
vm._update(vnode, hydrating)
mark(endTag)
measure(`vue ${name} patch`, startTag, endTag)
}
} else {
updateComponent = () => {
vm._update(vm._render(), hydrating)
}
}
// we set this to vm._watcher inside the watcher's constructor
// since the watcher's initial patch may call $forceUpdate (e.g. inside child
// component's mounted hook), which relies on vm._watcher being already defined
//渲染watch
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'beforeUpdate')
}
}
}, true /* isRenderWatcher */)
hydrating = false
// manually mounted instance, call mounted on self
// mounted is called for render-created child components in its inserted hook
if (vm.$vnode == null) {
vm._isMounted = true
callHook(vm, 'mounted')
}
return vm
}在src/core/instance/lifecycle.js文件中,将el(DOM)缓存到vm.$el,然后判断有没有render函数,没有render函数并且template没有准确转换成render函数,则创建一个createEmptyVNode(空 VNode ),开发环境会报警告。①例如定义了template但是第一个字符不是“#”,即在用 runtime-only 版本,又写了template options render函数,就会报这个警告。②还有就是写了template,但是没用这个编译版本,所以不会生成render函数,也会报错。即用了 runtime-only 版本,但是没有直接写render函数,template不可编译。③还有一种情况是没有template也没有render函数,会报else下的警告。总的来说就是没正确生成render函数。
然后定义了updateComponent函数,函数调用了vm._update,vm._update的第一个参数是vm._render()渲染出来的 VNode ,hydrating跟渲染相关,可以认为是false。updateComponent的执行是调用了new Watcher,这是一个渲染Watcher。Watcher是跟响应式原理强相关的类,实际上是一个观察者模式,有很多自定义Watcher,也有渲染Watcher。Watcher的定义在src/core/observer/watcher.js文件里。
Watcher实际上也是一个 class ,传入的第一个参数是vm,就是当前的 vue 实例。然后是updateComponent函数,第三个是noop(空 function ),然后是配置,也是对象。第五个是个 Boolean 值。跟src/core/observer/watcher.js的定义一一对应。isRenderWatcher是否是渲染 Watcher 的标志位。传 true 时,就在vm上增加_watcher,然后把所有都push到vm._watchers里。
如果expOrFn是函数,则getter复制函数,否则调用parsePath把expOrFn转化成getter。会在get()中调用一次getter,就执行到updateComponent方法了,就会执行vm._update(vm._render(), hydrating)。
// src/core/observer/watcher.js
export default class Watcher {
vm: Component;
expression: string;
cb: Function;
id: number;
deep: boolean;
user: boolean;
lazy: boolean;
sync: boolean;
dirty: boolean;
active: boolean;
deps: Array<Dep>;
newDeps: Array<Dep>;
depIds: SimpleSet;
newDepIds: SimpleSet;
before: ?Function;
getter: Function;
value: any;
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
this.vm = vm
if (isRenderWatcher) {
vm._watcher = this
}
vm._watchers.push(this)
// options
if (options) {
this.deep = !!options.deep
this.user = !!options.user
this.lazy = !!options.lazy
this.sync = !!options.sync
this.before = options.before
} else {
this.deep = this.user = this.lazy = this.sync = false
}
this.cb = cb
this.id = ++uid // uid for batching
this.active = true
this.dirty = this.lazy // for lazy watchers
this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()
this.expression = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: ''
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn
} else {
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = noop
process.env.NODE_ENV !== 'production' && warn(
`Failed watching path: "${expOrFn}" ` +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
)
}
}
this.value = this.lazy
? undefined
: this.get()
}
/**
* Evaluate the getter, and re-collect dependencies.
*/
get () {
pushTarget(this)
let value
const vm = this.vm
try {
value = this.getter.call(vm, vm)
} catch (e) {
if (this.user) {
handleError(e, vm, `getter for watcher "${this.expression}"`)
} else {
throw e
}
} finally {
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
}
return value
}
/**
* Add a dependency to this directive.
*/
addDep (dep: Dep) {
const id = dep.id
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id)
this.newDeps.push(dep)
if (!this.depIds.has(id)) {
dep.addSub(this)
}
}
}
/**
* Clean up for dependency collection.
*/
cleanupDeps () {
let i = this.deps.length
while (i--) {
const dep = this.deps[i]
if (!this.newDepIds.has(dep.id)) {
dep.removeSub(this)
}
}
let tmp = this.depIds
this.depIds = this.newDepIds
this.newDepIds = tmp
this.newDepIds.clear()
tmp = this.deps
this.deps = this.newDeps
this.newDeps = tmp
this.newDeps.length = 0
}
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
run () {
if (this.active) {
const value = this.get()
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
const oldValue = this.value
this.value = value
if (this.user) {
const info = `callback for watcher "${this.expression}"`
invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info)
} else {
this.cb.call(this.vm, value, oldValue)
}
}
}
}
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
evaluate () {
this.value = this.get()
this.dirty = false
}
/**
* Depend on all deps collected by this watcher.
*/
depend () {
let i = this.deps.length
while (i--) {
this.deps[i].depend()
}
}
/**
* Remove self from all dependencies' subscriber list.
*/
teardown () {
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed.
if (!this.vm._isBeingDestroyed) {
remove(this.vm._watchers, this)
}
let i = this.deps.length
while (i--) {
this.deps[i].removeSub(this)
}
this.active = false
}
}
}5)总而言之,先对el做解析,判断render function,没有render则转换成template,template最终会编译成render。也就是说 Vue 只认render函数。
主要了解了$mount的实现,在compiler版本下,是对el做处理然后如果没定义render函数获取render函数,也就是把template通过一系列逻辑判断转换成render。**template有很多种写法,可以写template,也可以template是一个 dom ,不写的话通过el获取template,然后把template通过编译的手段转化成render函数。**也就是说$mount在compiler版本的前提就是首先拿到render函数,然后调用mountComponent方法。mountComponent方法定义了mountComponent函数,这个函数实际上是一个渲染Watcher。通过Watcher是因为updateComponent实际上是执行了一次渲染,这个渲染过程除了首次渲染之后在更新Watcher还会触发updateComponent方法。updateComponent是监听到执行的一个过程,当数据发生变化,视图修改入口也是updateComponent方法。这就是渲染Watcher要做的事情。
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧