首先讓我們從最簡單的一個(gè)實(shí)例Vue入手:
const app = new Vue({ // options 傳入一個(gè)選項(xiàng)obj.這個(gè)obj即對(duì)于這個(gè)vue實(shí)例的初始化 })通過查閱文檔,我們可以知道這個(gè)options可以接受:
具體未展開的內(nèi)容請(qǐng)自行查閱相關(guān)文檔,接下來讓我們來看看傳入的選項(xiàng)/數(shù)據(jù)是如何管理數(shù)據(jù)之間的相互依賴的。
const app = new Vue({ el: '#app', props: { a: { type: Object, default () { return { key1: 'a', key2: { a: 'b' } } } } }, data: { msg1: 'Hello world!', arr: { arr1: 1 } }, watch: { a (newVal, oldVal) { console.log(newVal, oldVal) } }, methods: { go () { console.log('This is simple demo') } } })我們使用Vue這個(gè)構(gòu)造函數(shù)去實(shí)例化了一個(gè)vue實(shí)例app。傳入了props, data, watch, methods等屬性。在實(shí)例化的過程中,Vue提供的構(gòu)造函數(shù)就使用我們傳入的options去完成數(shù)據(jù)的依賴管理,初始化的過程只有一次,但是在你自己的程序當(dāng)中,數(shù)據(jù)的依賴管理的次數(shù)不止一次。
那Vue的構(gòu)造函數(shù)到底是怎么實(shí)現(xiàn)的呢?Vue
// 構(gòu)造函數(shù)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)}// 對(duì)Vue這個(gè)class進(jìn)行mixin,即在原型上添加方法// Vue.prototype.* = function () {}initMixin(Vue)stateMixin(Vue)eventsMixin(Vue)lifecycleMixin(Vue)renderMixin(Vue)當(dāng)我們調(diào)用new Vue的時(shí)候,事實(shí)上就調(diào)用的Vue原型上的_init方法.
// 原型上提供_init方法,新建一個(gè)vue實(shí)例并傳入options參數(shù) Vue.prototype._init = function (options?: Object) { const vm: Component = this // a uid vm._uid = uid++ let startTag, endTag // 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 { // 將傳入的這些options選項(xiàng)掛載到vm.$options屬性上 vm.$options = mergeOptions( // components/filter/directive resolveConstructorOptions(vm.constructor), // this._init()傳入的options options || {}, vm ) } /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { initProxy(vm) } else { vm._renderProxy = vm } // expose real self vm._self = vm // 自身的實(shí)例 // 接下來所有的操作都是在這個(gè)實(shí)例上添加方法 initLifecycle(vm) // lifecycle初始化 initEvents(vm) // events初始化 vm._events, 主要是提供vm實(shí)例上的$on/$emit/$off/$off等方法 initRender(vm) // 初始化渲染函數(shù),在vm上綁定$createElement方法 callHook(vm, 'beforeCreate') // 鉤子函數(shù)的執(zhí)行, beforeCreate initInjections(vm) // resolve injections before data/props initState(vm) // Observe data添加對(duì)data的監(jiān)聽, 將data轉(zhuǎn)化為getters/setters initProvide(vm) // resolve provide after data/props callHook(vm, 'created') // 鉤子函數(shù)的執(zhí)行, created // vm掛載的根元素 if (vm.$options.el) { vm.$mount(vm.$options.el) } }
新聞熱點(diǎn)
疑難解答
圖片精選