I am working on a website with different page setups.
My setup is not an SPA and so I do not have the privalige of one single root instance.
This means that if I create a component I have to register a root vue instance every time I want to use my component.
I create my custom component as a global component:
Vue.component('mycomponent', { /* options */ });
According to the vue docs I have to register a root instance in order to use my component
new Vue({ el: '#root-instance' });
<div class="header" id="root-instance">
<mycomponent></mycomponent>
</div>
Then in a different section I want to use the same component but I have to create another root instance:
new Vue({ el: '#other-root-instance' });
<div class="sidebar" id="other-root-instance">
<mycomponent></mycomponent>
</div>
I tried using a class for instantiating, something like:
new Vue({ el: '.root-instance' });
But view only loads this once.
Is there any way to load a component but not instantiate a root instance every time I use it?
Note: I have several root instances on the page and therefore can not declare a single root instance for the page. Effectively I do not want to make my page a Single Page App.
To create a component, following is the syntax. Vue. component('nameofthecomponent',{ // options}); Once a component is created, the name of the component becomes the custom element and the same can be used in the Vue instance element created, i.e. inside the div with ids component_test and component_test1.
The $el option in Vue provides Vue with an existing HTML element to mount the Vue instance generated using the new keyword. this. $el. querySelector is used to access HTML elements and modify the element's properties.
STEP 01: First, Import the Child Component into the Parent Component inside script tag but above export default function declaration. STEP 02: Then, Register the Child Component inside the Parent Component by adding it to components object. STEP 03: Finally, Use the Child Component in the Parent Component Template.
You don't have to wrap your component in a root instance div, you can make the component tag the root instance.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With