怎麼在Vue的某個組件中根據組件tag標籤名獲取到對應的VueComponent實例呢

 

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是該方法的意義名)
相關文章
相關標籤/搜索