1.以前玩omi框架的時候,有Omi.get方法來獲取實例, ...好久沒玩了,忘了。
反正很喜歡該方法。
2.如今想在vue里面怎么能夠快速獲取到對應組件標簽名的的實例呢?
3.文檔也看過,似乎腦海中沒啥印象獲取獲取,除了ref或者vm.$children,這個只能獲取到父子關系,或者爺孫...等關系,反正比較麻煩
4.那就全局注冊個$_live_getChildComponent方法,每個實例便有了改方法。
5.使用 this.$_live_getChildComponent('vue實例', '組件tag名')
// 全局混入一些工具方法(根據自定義標簽名(組件名)獲取某個Vue實例的孩子組件),該方法會注冊到每一個Vue實例上。 Vue.mixin({ created: function() { let Type = (function() { let Type = {}; for (let i = 0, type; type = ['Undefined', 'Null', 'Boolean', 'Number', 'String', 'Function', 'Array', 'Object'][i++]; ) { (function(type) { Type['is' + type] = function(obj) { return Object.prototype.toString.call(obj) === '[object ' + type + ']'; }; })(type); } return Type; })(); this.$_live_type = Type; // use: this.$getChildComponent(vm, 'xx-xx') this.$_live_getChildComponent = function(vueInstance, componentTag) { let component = null; let allComp = getAllChildComp(vueInstance); let i = allComp.findIndex(function(vm) { return vm.$options._componentTag === componentTag; }); if (i !== -1) { component = allComp[i]; } return component; function getAllChildComp(instance) { let allComp = [], child; if (Type.isObject(instance)) { child = instance.$children; } else if (Type.isArray(instance)) { child = instance; } for (let i = 0; i < child.length; i++) { allComp.push(child[i]); if (child[i].$children.length > 0) { // 還有孩子 allComp = allComp.concat(getAllChildComp(child[i].$children)) }; } return allComp; } }; } });
注: 至於$_live_getChildComponent這他媽什么命名,其實我也不太喜歡,但是Evan You是這么說的,我也只好遵守了。
在插件、混入等擴展中始終為自定義的私有屬性使用 $_ 前綴。並附帶一個命名空間以回避和其它作者的沖突 (比如 $_yourPluginName_)。
$_live_getChildComponent($_為前綴, live是我目前開發的項目名稱, getChildComponent是該方法的意義名)