Vue 2.0 中依賴注入 provide/inject組合實戰(zhàn)
用法
--------------------------------------------------------------------------------
先來看看官網(wǎng)的介紹:
簡單的說,當(dāng)組件的引入層次過多,我們的子孫組件想要獲取祖先組件得資源,那么怎么辦呢,總不能一直取父級往上吧,而且這樣代碼結(jié)構(gòu)容易混亂。這個就是這對選項要干的事情
provide和inject需要配合使用,它們的含義如下:
provide ;一個對象或返回一個對象的函數(shù),該對象包含可注入起子孫的屬性,可以使用ES6的Symbols作為key(只有原生支持Symbol才可以)
inject ;一個字符串?dāng)?shù)組或一個對象
;字符串?dāng)?shù)組 ;provide對象里哪些屬性可用
;一個對象 ;key是本地的綁定名,value是provide里對應(yīng)的對象名,也可以是一個對象,此時from屬性是provide里對應(yīng)的對象名,default屬性是不存在時的默認值
來個實例就明顯了:
<!DOCTYPE html> <!--例1--> <html lang="en"> <head> <meta charset="UTF-8"> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script> <title>Document</title> </head> <body> <div id="app"><child></child></div> <script> Vue.component('child',{ inject:['message'], template:'<p>{{message}}</p>' }) new Vue({ el:'#app',provide:{message:'Hello Vue!'} }) </script> </body> </html>
輸出:Hello Vue!,對應(yīng)的DOM節(jié)點渲染為:
是不是感覺和props的傳值差不多,我們在中間再嵌套一層組件就知道他的用處了,例如:
<!DOCTYPE html> <!--例2--> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script> </head> <body> <div id="app"><test></test></div> <script> Vue.component('child',{ inject:['message'], template:'<p>{{message}}</p>' }) Vue.component('test',{ template:`<div><child></child></div>` }) new Vue({ el:'#app',provide:{message:'Hello Vue!'} }) </script> </body> </html>
輸出:Hello Vue!,對應(yīng)的DOM節(jié)點渲染為:
就是這個用處吧,多層嵌套時還是很方便的
源碼分析
--------------------------------------------------------------------------------
provide/inject組合的源碼分為三個部分,分別是組件注冊、Vue實例化和組件實例化的過程,如下:
組件注冊時
注冊時會執(zhí)行Vue.extend()(第4770行),內(nèi)部會執(zhí)行mergeOptions()合并一些屬性,mergeOptions如下:
function mergeOptions ( //第1451行 parent, child, vm ) { { checkComponents(child); } if (typeof child === 'function') { child = child.options; } normalizeProps(child, vm); normalizeInject(child, vm); //對inject進行一次規(guī)范化 normalizeDirectives(child); var extendsFrom = child.extends; if (extendsFrom) { parent = mergeOptions(parent, extendsFrom, vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } var options = {}; var key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField (key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options }
normalizeInject定義如下:
function normalizeInject (options, vm) { //第1398行 var inject = options.inject; if (!inject) { return } var normalized = options.inject = {}; if (Array.isArray(inject)) { //如果inject是一個數(shù)組 for (var i = 0; i < inject.length; i++) { //遍歷inject normalized[inject[i]] = { from: inject[i] }; //保存到normalized里面,例如:{foo: {from: "foo"}} } } else if (isPlainObject(inject)) { //如果inject是一個對象 for (var key in inject) { var val = inject[key]; normalized[key] = isPlainObject(val) ? extend({ from: key }, val) : { from: val }; } } else { warn( "Invalid value for option \"inject\": expected an Array or an Object, " + "but got " + (toRawType(inject)) + ".", vm ); } }
對于例1來說,mergeOptions()之后inject等于:{message: {from: "message"}},
如下:
Vue實例化時
執(zhí)行_init()時會執(zhí)行mergeOptions()
進行數(shù)據(jù)的合并,對于provide的合并策略等于mergeDataOrFn()
函數(shù)(和data的合并策略是一樣的,定義在1321行),返回一個匿名函數(shù)(第1154行),如下:
function mergeDataOrFn ( //第1154行 parentVal, childVal, vm ) { if (!vm) { //這是組件的分支 // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( typeof childVal === 'function' ? childVal.call(this, this) : childVal, typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal ) } } else { //這是非組件的實例,返回一個函數(shù) return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm, vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm, vm) : parentVal; if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } }
然后返回到_init()之后會調(diào)用initProvide()初始化provide:
function initProvide (vm) { //第3619行 var provide = vm.$options.provide; //嘗試獲取provide if (provide) { //如果provide存在,當(dāng)它是函數(shù)時執(zhí)行該返回,否則直接將provide保存到Vue實例的_provided屬性上 vm._provided = typeof provide === 'function' ? provide.call(vm) : provide; } }
返回后_provided等于{message:"Hello Vue!"},
如下
e]
組件實例化時
_init()時會執(zhí)行initInjections(),
經(jīng)過了前面兩步的處理,這里比較簡單了,直接從父Vue或父Vue的父Vue獲取對應(yīng)的值即可,如下:
function initInjections (vm) { //第2681行 初始化inject var result = resolveInject(vm.$options.inject, vm); //遍歷祖先節(jié)點,獲取對應(yīng)的inject,例如:比如:{foo: "bar"} if (result) { //如果獲取了對應(yīng)的值,則將它變成響應(yīng)式 toggleObserving(false); Object.keys(result).forEach(function (key) { /* istanbul ignore else */ { defineReactive(vm, key, result[key], function () { //將key編程響應(yīng)式,這樣就可以訪問該元素了 warn( "Avoid mutating an injected value directly since the changes will be " + "overwritten whenever the provided component re-renders. " + "injection being mutated: \"" + key + "\"", vm ); }); } }); toggleObserving(true); } } function resolveInject (inject, vm) { //第3649行 確定Inject inject:例如:{foo: {from: "foo"}} vm:當(dāng)前組件的實例 if (inject) { //如果inject非空 // inject is :any because flow is not smart enough to figure out cached var result = Object.create(null); //存儲最后的結(jié)果 var keys = hasSymbol ? Reflect.ownKeys(inject).filter(function (key) { //如果有符號類型,調(diào)用Reflect.ownKeys()返回所有的key,再調(diào)用filter /* istanbul ignore next */ return Object.getOwnPropertyDescriptor(inject, key).enumerable }) : Object.keys(inject); //獲取所有的key,此時keys就是個字符串?dāng)?shù)組,比如:["foo"] for (var i = 0; i < keys.length; i++) { //這里遍歷每個key var key = keys[i]; var provideKey = inject[key].from; var source = vm; while (source) { if (source._provided && hasOwn(source._provided, provideKey)) { //如果source存在_provided 且 含有provideKey這個屬性 result[key] = source._provided[provideKey]; //則將值保存到result[key]中 break //并跳出while循環(huán) } source = source.$parent; //否則將source賦值給父Vue實例,直到找到對應(yīng)的providekey為止 } if (!source) { //如果最后source不存在,即沒有從當(dāng)前實例或祖先實例的_provide找到privideKey這個key if ('default' in inject[key]) { var provideDefault = inject[key].default; //如果有定義defult,則使用默認值 result[key] = typeof provideDefault === 'function' ? provideDefault.call(vm) : provideDefault; } else { warn(("Injection \"" + key + "\" not found"), vm); } } } return result //返回結(jié)果,比如:{foo: "bar"} } }
注:provide 和 inject 綁定并不是可響應(yīng)的。這是刻意為之的。然而,如果你傳入了一個可監(jiān)聽的對象,那么其對象的屬性還是可響應(yīng)的。
總結(jié)
以上所述是小編給大家介紹的Vue 2.0 中依賴注入 provide/inject組合實戰(zhàn),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
深入理解Vue父子組件生命周期執(zhí)行順序及鉤子函數(shù)
本文通過實例代碼給大家介紹了Vue父子組件生命周期執(zhí)行順序及鉤子函數(shù)的相關(guān)知識,非常不錯,具有一定的參考借鑒價值,需要的朋友參考下吧2018-08-08vue項目打包后提交到git上為什么沒有dist這個文件的解決方法
這篇文章主要介紹了vue項目打包后提交到git上為什么沒有dist這個文件的解決方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09如何利用vue-cli監(jiān)測webpack打包與啟動時長
這篇文章主要給大家介紹了關(guān)于如何利用vue-cli監(jiān)測webpack打包與啟動時長的相關(guān)資料,文中通過實例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-02-02