您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“Vue中響應(yīng)式系統(tǒng)實(shí)現(xiàn)原理是什么”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
每個(gè)組件實(shí)例都會(huì)對(duì)應(yīng)一個(gè)watcher實(shí)例,在組件渲染過(guò)程中把接觸過(guò)的數(shù)據(jù)property記錄為依賴(lài)。當(dāng)依賴(lài)項(xiàng)的setter觸發(fā)時(shí),會(huì)通知watcher,重新渲染組件
vue實(shí)例中的data選項(xiàng),在初始化時(shí)會(huì)遍歷該對(duì)象所有屬性,并使用Object.defineProperty轉(zhuǎn)為getter/setter。
Observer:主要是將對(duì)象轉(zhuǎn)為響應(yīng)式對(duì)象,在getter中,會(huì)創(chuàng)建Dep來(lái)收集依賴(lài)
Dep:用于存放watcher,即副作用函數(shù)effectFn
Watcher:觀察者,當(dāng)有數(shù)據(jù)更新時(shí),會(huì)觸發(fā)update
在src/core/instance/lifecycle.ts中的mountComponent中
export function mountComponent( vm: Component, el: Element | null | undefined, hydrating?: boolean ): Component { vm.$el = el callHook(vm, 'beforeMount') let updateComponent /* istanbul ignore if */ updateComponent = () => { vm._update(vm._render(), hydrating) } const watcherOptions: WatcherOptions = { before() { if (vm._isMounted && !vm._isDestroyed) { callHook(vm, 'beforeUpdate') } } } // 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, watcherOptions, true /* isRenderWatcher */ ) hydrating = false // flush buffer for flush: "pre" watchers queued in setup() const preWatchers = vm._preWatchers if (preWatchers) { for (let i = 0; i < preWatchers.length; i++) { preWatchers[i].run() } } // 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/state.ts/initData中,主要是observe(data)這個(gè)
function initData(vm: Component) { let data: any = vm.$options.data data = vm._data = isFunction(data) ? getData(data, vm) : data || {} if (!isPlainObject(data)) { data = {} } // 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 (props && hasOwn(props, key)) { } else if (!isReserved(key)) { proxy(vm, `_data`, key) } } // observe data const ob = observe(data) ob && ob.vmCount++ }
Observer只追蹤數(shù)據(jù)是否被修改,無(wú)法追蹤新增和刪除屬性
Vue提供了Vue.prototype.$set和Vue.prototype.$delete,內(nèi)部也是調(diào)用Observer的方法
import { set, del } from '../observer/index' Vue.prototype.$set = set Vue.prototype.$delete = del
“Vue中響應(yīng)式系統(tǒng)實(shí)現(xiàn)原理是什么”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。