I'm new to Vue.js.
I want to register a local component as described over here:
https://v2.vuejs.org/v2/guide/components.html#Local-Registration
The only issue is that I need to register a component to an existing Vue instance not while creating a new instance something like:
const app = new Vue({
el: '#app'
});
app.component({
'my-component': {
template: '<div>A custom component!</div>'
}
});
I have tried Vue.extend for that, but it is not working.
Edit:
Why I need this:
I'm creating a 3rd party package which will have that component. The framework on which this package is going to be installed will already have Vue.js included and a Vue instance. So if I include my package's JS before framework's JS, then it will give me Vue is undefined and if I include my package's JS after framework's JS, then it will give me component error as it has to be registered before the Vue instantiation.
Using Local Registration in a Module System vue or . js file(Here, the component A and component C are being used inside the component B file ): import ComponentA from './ComponentA' import ComponentC from './ComponentC' export default { components: { ComponentA, ComponentC }, // ... }
When we want to globally register a component in Vue, we need to do it in this file. All you have to do is import your component, as you usually would, and then register it using app. component . import { createApp } from 'vue' import App from './App.
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.
Global components should be declared before new instance construct.
Vue.component('my-component-a', {
template: '<div>A custom component A!</div>'
});
Vue.component('my-component-b', {
template: '<div>A custom component B!</div>'
});
const app1 = new Vue({
el: '#app1',
template: '<div><my-component-a /><my-component-b /><my-component-c /></div>',
components: {
MyComponentC: {
template: '<div>A custom component C!</div>'
}
}
});
const app2 = new Vue({
el: '#app2',
template: '<div><my-component-b /><my-component-a /><my-component-c /></div>'
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app1"></div>
<div id="app2"></div>
You don't have access to the C component from within your app2
You can't add components to an instance like that. All you can do it adding them to the Vue constructor like usual:
Vue.component('my-component', {
template: '<div>A custom component!</div>'
});
const app = new Vue({
el: '#app'
});
See a demo here: https://jsfiddle.net/Linusborg/kb9pbecq/
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