代码之家  ›  专栏  ›  技术社区  ›  Oliver Williams

VueJS-页面上所有vue实例的列表

  •  1
  • Oliver Williams  · 技术社区  · 6 年前

    很简单,给出如下代码 new Vue()

    <div id="instance1">
    {{ name }}
    </div>
    <div id="instance2">
    {{ name }}
    </div>
    <my-component id="some-element"></my-component>
    

    Javascript代码:

    new Vue({
      el: '#instance1',
      data: {
        name: 'Sammy',
      }
    });
    
    new Vue({
      el: '#instance2',
      data: {
        name: 'Bobby',
      }
    });
    
    Vue.component('my-component', {
      data: function(){
        return {
          name: 'Mark',
        }
      },
      template: '<div>Hello: {{ name }}</div>',
    });
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Harshal Patil    6 年前

    你不能真的那样做。你得自己维护柜台。这意味着您必须将每个调用包装到 new Vue()

    let counter = 0;
    const rootVueComponents = [];
    
    function makeRootInstance(el, data) {
        const instance = new Vue(el, data);
    
        rootVueComponents.push(instance);
        counter++;
    
        return instance;
    }
    

    同样,这只会为您提供根Vue实例的列表。如果您有一个组件层次结构,那么它将不起作用。

    最后,如果您真的希望有一个所有组件的列表,那么创建一个全局 created() 混合所有的Vue组件并在那里保持这个计数逻辑。

    还有,我想知道你为什么需要这个。我不认为有必要这么做,除非你在试验。

    推荐文章