如何在不实例化根实例的情况下使用 vue 组件?
How do I use a vue component without instantiating a root instance?
详情
我正在使用不同页面设置的网站上工作。
我的设置不是 SPA,因此我没有单一根实例的特权。
问题
这意味着如果我创建一个组件,每次我想使用我的组件时都必须注册一个根 vue 实例。
问题示例
我将自定义组件创建为全局组件:
Vue.component('mycomponent', { /* options */ });
根据 vue 文档,我必须注册一个根实例才能使用我的组件
new Vue({ el: '#root-instance' });
<div class="header" id="root-instance">
<mycomponent></mycomponent>
</div>
然后在不同的部分我想使用相同的组件但我必须创建另一个根实例:
new Vue({ el: '#other-root-instance' });
<div class="sidebar" id="other-root-instance">
<mycomponent></mycomponent>
</div>
我尝试使用 class 进行实例化,例如:
new Vue({ el: '.root-instance' });
但是视图只加载一次。
问题
有什么方法可以加载组件而不是每次使用时都实例化根实例吗?
注意:我在页面上有多个根实例,因此无法为页面声明单个根实例。实际上,我不想让我的页面成为单页应用程序。
您不必将组件包装在根实例中div,您可以将组件标签设为根实例。
Vue.component('myComponent', {
props: ['custom'],
template: '<div>Hi there, I am the {{custom}}</div>'
});
new Vue({
el: '#sidebar'
});
new Vue({
el: '#topmenu'
});
<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>
详情
我正在使用不同页面设置的网站上工作。
我的设置不是 SPA,因此我没有单一根实例的特权。
问题
这意味着如果我创建一个组件,每次我想使用我的组件时都必须注册一个根 vue 实例。
问题示例
我将自定义组件创建为全局组件:
Vue.component('mycomponent', { /* options */ });
根据 vue 文档,我必须注册一个根实例才能使用我的组件
new Vue({ el: '#root-instance' });
<div class="header" id="root-instance">
<mycomponent></mycomponent>
</div>
然后在不同的部分我想使用相同的组件但我必须创建另一个根实例:
new Vue({ el: '#other-root-instance' });
<div class="sidebar" id="other-root-instance">
<mycomponent></mycomponent>
</div>
我尝试使用 class 进行实例化,例如:
new Vue({ el: '.root-instance' });
但是视图只加载一次。
问题
有什么方法可以加载组件而不是每次使用时都实例化根实例吗?
注意:我在页面上有多个根实例,因此无法为页面声明单个根实例。实际上,我不想让我的页面成为单页应用程序。
您不必将组件包装在根实例中div,您可以将组件标签设为根实例。
Vue.component('myComponent', {
props: ['custom'],
template: '<div>Hi there, I am the {{custom}}</div>'
});
new Vue({
el: '#sidebar'
});
new Vue({
el: '#topmenu'
});
<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>