VueJS - 页面上所有vue实例的第一个

问题描述 投票:1回答:1

很简单,给定类似下面的代码,混合使用new Vue()实例和组件,如何在页面上列出所有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>',
});
vue.js
1个回答
2
投票

你真的不能这样做。你必须自己维护柜台。这意味着你必须将每次调用包装到new Vue(),如:

let counter = 0;
const rootVueComponents = [];

function makeRootInstance(el, data) {
    const instance = new Vue(el, data);

    rootVueComponents.push(instance);
    counter++;

    return instance;
}

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

最后,如果你真的希望得到所有组件的列表,那么为所有Vue组件创建一个全局created() mixin并在那里维护这个计数逻辑。

另外,我想知道为什么你可能需要这个。我不认为真正需要这样做,除非你正在试验。

© www.soinside.com 2019 - 2024. All rights reserved.