问题
I'm new to Vue.js.
I want to register a local component as described over here:
https://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.
回答1:
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/vue@2.5.17/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
回答2:
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/
回答3:
const app = new Vue({
el: '#app',
components: {
'my-component': {template: '<div>Text in component</div>'}
}
});
回答4:
Basically, you can not register a component to a existing Vue instance while it was already rendered.But you can register a component before the Vue instance mounted into the dom element.
// local component
var child = {
template: '<div>A custom component!</div>'
}
const app = new Vue({
el: '#app',
components: {
Child: child
}
})
or
// global component
Vue.component({
'child': {
template: '<div>A custom component!</div>'
} })
Define the component first and then implement it.
来源:https://stackoverflow.com/questions/45481822/register-a-component-to-an-existing-vue-js-instance