您好,登錄后才能下訂單哦!
本篇內容介紹了“Vue中響應式系統實現原理是什么”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
每個組件實例都會對應一個watcher實例,在組件渲染過程中把接觸過的數據property記錄為依賴。當依賴項的setter觸發時,會通知watcher,重新渲染組件
vue實例中的data選項,在初始化時會遍歷該對象所有屬性,并使用Object.defineProperty轉為getter/setter。
Observer:主要是將對象轉為響應式對象,在getter中,會創建Dep來收集依賴
Dep:用于存放watcher,即副作用函數effectFn
Watcher:觀察者,當有數據更新時,會觸發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)這個
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只追蹤數據是否被修改,無法追蹤新增和刪除屬性
Vue提供了Vue.prototype.$set和Vue.prototype.$delete,內部也是調用Observer的方法
import { set, del } from '../observer/index' Vue.prototype.$set = set Vue.prototype.$delete = del
“Vue中響應式系統實現原理是什么”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。