如何在不实例化根实例的情况下使用vue组件?

hit*_*uct 6 vue.js vue-component vuejs2

细节

我正在使用不同页面设置的网站上工作.

我的设置不是SPA,因此我没有单个根实例的私有化.

问题

这意味着如果我创建一个组件,每次我想使用我的组件时都必须注册一个root vue实例.

问题示例

我将自定义组件创建为全局组件:

Vue.component('mycomponent', { /* options */ });
Run Code Online (Sandbox Code Playgroud)

根据vue文档,我必须注册一个根实例才能使用我的组件

new Vue({ el: '#root-instance' });

<div class="header" id="root-instance">
  <mycomponent></mycomponent>
</div>
Run Code Online (Sandbox Code Playgroud)

然后在另一个部分我想使用相同的组件,但我必须创建另一个根实例:

new Vue({ el: '#other-root-instance' });

<div class="sidebar" id="other-root-instance">
  <mycomponent></mycomponent>
</div>
Run Code Online (Sandbox Code Playgroud)

我尝试使用类进行实例化,例如:

new Vue({ el: '.root-instance' });
Run Code Online (Sandbox Code Playgroud)

但是视图只加载一次.

是否有任何方法可以加载组件但不会在每次使用时实例化根实例?

注意:我在页面上有几个根实例,因此无法为页面声明单个根实例.实际上,我不想让我的页面成为单页面应用程序.

Roy*_*y J 5

您不必将组件包装在根实例div中,您可以使组件标记为根实例.

Vue.component('myComponent', {
  props: ['custom'],
  template: '<div>Hi there, I am the {{custom}}</div>'
});

new Vue({
  el: '#sidebar'
});

new Vue({
  el: '#topmenu'
});
Run Code Online (Sandbox Code Playgroud)
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.min.js"></script>

<my-component id="sidebar" custom="sidebar"></my-component>
<div>
Some stuff that is not under Vue control {{custom}}
</div>
<my-component id="topmenu" custom="top menu"></my-component>
Run Code Online (Sandbox Code Playgroud)