數(shù)據(jù)驅(qū)動(dòng)
Vue.js 一個(gè)核心思想就是數(shù)據(jù)驅(qū)動(dòng)
類比:
jquery缺點(diǎn):直接操作dom 增加內(nèi)存使用(把DOM與javascript各自想象成為島嶼,它們之間用收費(fèi)橋梁鏈接的晤硕。訪問DOM次數(shù)越多性置,費(fèi)用就越高捻浦,推薦的做法是盡可能的減少過橋的次數(shù)绢掰,努力呆在ECMscript島嶼上没酣。)
new Vue 時(shí)到底干了啥
new關(guān)鍵字在 Javascript 語(yǔ)言中代表實(shí)例化是一個(gè)對(duì)象舀患,而?Vue?實(shí)際上是一個(gè)類蚓峦,類在 Javascript 中是用 Function 來(lái)實(shí)現(xiàn)的
源碼舌剂,在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)
}
new初始化vue后? 再調(diào)用? this._init() 方法 在src/core/instance/init.js
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 being observed
? vm._isVue = true
? // merge options
? if (options && options._isComponent) {
? ? // optimize internal component instantiation
? ? // since dynamic options merging is pretty slow, and none of the
? ? // internal component options needs special treatment.
? ? initInternalComponent(vm, options)
? } else {
? ? vm.$options = mergeOptions(
? ? ? resolveConstructorOptions(vm.constructor),
? ? ? options || {},
? ? ? vm
? ? )
? }
? /* istanbul ignore else */
? if (process.env.NODE_ENV !== 'production') {
? ? initProxy(vm)
? } else {
? ? vm._renderProxy = vm
? }
? // expose real self
? vm._self = vm
? initLifecycle(vm)
? initEvents(vm)
? initRender(vm)
? callHook(vm, 'beforeCreate')
? initInjections(vm) // resolve injections before data/props
? initState(vm)
? initProvide(vm) // resolve provide after data/props
? callHook(vm, 'created')
? /* istanbul ignore if */
? if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
? ? vm._name = formatComponentName(vm, false)
? ? mark(endTag)
? ? measure(`vue ${vm._name} init`, startTag, endTag)
? }
? if (vm.$options.el) {
? ? vm.$mount(vm.$options.el)
? }
}
Vue 初始化主要就干了幾件事情,合并配置暑椰,初始化生命周期霍转,初始化事件中心,初始化渲染干茉,初始化 data谴忧、props、computed角虫、watcher 等等
在初始化的最后沾谓,檢測(cè)到如果有?el?屬性,則調(diào)用?vm.$mount?方法掛載?vm戳鹅,掛載的目標(biāo)就是把模板渲染成最終的 DOM
initState() 做了什么事情
initData 拿出 vue 中data里的數(shù)據(jù)? 賦值給 vm._data 同時(shí)拿到props 和 methods均驶。?
最終使用proxy函數(shù)將 數(shù)據(jù)進(jìn)行代理? 例如:this.message =>? this._data.message
function initData (vm: Component) {
? let data = vm.$options.data
? data = vm._data = typeof data === 'function'
? ? ? getData(data, vm)
? ? : data || {}
? if (!isPlainObject(data)) {
? ? data = {}
? ? process.env.NODE_ENV !== 'production' && warn(
? ? ? 'data functions should return an object:\n' +
? ? ? 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
? ? ? vm
? ? )
? }
? // proxy data on instance
? const keys = Object.keys(data)
? const props = vm.$options.props
? const methods = vm.$options.methods
? let i = keys.length
? while (i--) {
? ? const key = keys[i]
? ? if (process.env.NODE_ENV !== 'production') {
? ? ? if (methods && hasOwn(methods, key)) {
? ? ? ? warn(
? ? ? ? ? `Method "${key}" has already been defined as a data property.`,
? ? ? ? ? vm
? ? ? ? )
? ? ? }
? ? }
? ? if (props && hasOwn(props, key)) {
? ? ? process.env.NODE_ENV !== 'production' && warn(
? ? ? ? `The data property "${key}" is already declared as a prop. ` +
? ? ? ? `Use prop default value instead.`,
? ? ? ? vm
? ? ? )
? ? } else if (!isReserved(key)) {
? ? ? proxy(vm, `_data`, key)
? ? }
? }
? // observe data
? observe(data, true /* asRootData */)
}
Vue 實(shí)例掛載的實(shí)現(xiàn)
Vue 中我們是通過?$mount?實(shí)例方法去掛載?vm?的,$mount?方法在多個(gè)文件中都有定義枫虏,如?src/platform/web/entry-runtime-with-compiler.js妇穴、src/platform/web/runtime/index.js、src/platform/weex/runtime/index.js隶债。因?yàn)?$mount?這個(gè)方法的實(shí)現(xiàn)是和平臺(tái)腾它、構(gòu)建方式都相關(guān)的。
當(dāng) 拋開 webpack 的 vue-loader 死讹。??compiler? 是最接近我們本地開發(fā)的構(gòu)建? 在入口文件init.js中 使用$mounted() 方法進(jìn)行掛載DOM時(shí) 就使用了這個(gè)方法
const mount = Vue.prototype.$mount
// 之前已經(jīng)定義過的$mount方法 在文件入口處再次重新定義
Vue.prototype.$mount = function (
? el?: string | Element,
? hydrating?: boolean
): Component {
? el = el && query(el)
? /* istanbul ignore if */
? //?它對(duì)?el?做了限制瞒滴,Vue 不能掛載在?body、html?這樣的根節(jié)點(diǎn)上 vue本事會(huì)帶html和body節(jié)點(diǎn) 會(huì)導(dǎo)致覆蓋節(jié)點(diǎn) 提示報(bào)錯(cuò)? 這也就是平常開發(fā)中為何使用<div id="app"></div>的方式來(lái)掛載vue
? if (el === document.body || el === document.documentElement) {
??? process.env.NODE_ENV !== 'production' && warn(
????? `Do not mount Vue to or - mount to normal elements instead.`
??? )
??? return this
? }
? const options = this.$options
? // resolve template/el and convert to render function
? //?如果沒有定義?render?方法赞警,則會(huì)把?el?或者?template?字符串轉(zhuǎn)換成?render?方法
? //?在 Vue 2.0 版本中妓忍,所有 Vue 的組件的渲染最終都需要?render?方法,無(wú)論我們是用單文件 .vue 方式開發(fā)組件愧旦,還是寫了?el?或者?template?屬性世剖,最終都會(huì)轉(zhuǎn)換成?render?方法,那么這個(gè)過程是 Vue 的一個(gè)“在線編譯”的過程笤虫,它是調(diào)用?compileToFunctions?方法實(shí)現(xiàn)的
? if (!options.render) {
??? let template = options.template
? ? // 如果么有render 那么就讀取template 并且對(duì)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是DOM對(duì)象 則獲取html
??????? template = template.innerHTML
????? } else {
??????? if (process.env.NODE_ENV !== 'production') {
????????? warn('invalid template option:' + template, this)
??????? }
??????? return this
????? }
??? } else if (el) { // 如果template 木有DOM innerHTML 則會(huì)在外面包一個(gè)
????? template = getOuterHTML(el)
??? }
? ? // 編譯相關(guān)
??? if (template) {
????? /* istanbul ignore if */
????? if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
??????? mark('compile')
????? }
????? const { render, staticRenderFns } = compileToFunctions(template, {
??????? 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)
}
原先原型上的?$mount?方法在?src/platform/web/runtime/index.js?中定義旁瘫,之所以這么設(shè)計(jì)完全是為了復(fù)用祖凫,因?yàn)樗强梢员?runtimeonly?版本的 Vue 直接使用的。
Vue.prototype.$mount = function (
? el?: string | Element,
? hydrating?: boolean
): Component {
? el = el && inBrowser ? query(el) : undefined
? return mountComponent(this, el, hydrating)
}
$mount?方法支持傳入 2 個(gè)參數(shù)酬凳,第一個(gè)是?el蝙场,它表示掛載的元素,可以是字符串粱年,也可以是 DOM 對(duì)象,如果是字符串在瀏覽器環(huán)境下會(huì)調(diào)用?query?方法轉(zhuǎn)換成 DOM 對(duì)象的罚拟。第二個(gè)參數(shù)是和服務(wù)端渲染相關(guān)台诗,在瀏覽器環(huán)境下我們不需要傳第二個(gè)參數(shù)。
$mount?方法實(shí)際上會(huì)去調(diào)用?mountComponent?方法赐俗,這個(gè)方法定義在?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
? new Watcher(vm, updateComponent, noop, {
??? before () {
????? if (vm._isMounted) {
??????? 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
}
從上面的代碼可以看到拉队,mountComponent?核心就是先調(diào)用?vm._render?方法先生成虛擬 Node,再實(shí)例化一個(gè)渲染W(wǎng)atcher阻逮,在它的回調(diào)函數(shù)中會(huì)調(diào)用?updateComponent?方法粱快,最終調(diào)用?vm._update?更新 DOM。
Watcher?在這里起到兩個(gè)作用叔扼,一個(gè)是初始化的時(shí)候會(huì)執(zhí)行回調(diào)函數(shù)事哭,另一個(gè)是當(dāng) vm 實(shí)例中的監(jiān)測(cè)的數(shù)據(jù)發(fā)生變化的時(shí)候執(zhí)行回調(diào)函數(shù),
函數(shù)最后判斷為根節(jié)點(diǎn)的時(shí)候設(shè)置?vm._isMounted?為?true瓜富, 表示這個(gè)實(shí)例已經(jīng)掛載了鳍咱,同時(shí)執(zhí)行?mounted?鉤子函數(shù)。 這里注意?vm.$vnode?表示 Vue 實(shí)例的父虛擬 Node与柑,所以它為?Null?則表示當(dāng)前是根 Vue 的實(shí)例谤辜。