VueJs Local Components
are only available for use in the parent component with which they are registered.
Fragment component
You may get a console error telling you that you can't do something because yours is a fragment component. To solve this sort of issue just wrap your component template inside a single tag, like
a <div>
Local registration of components
A component can be registered either globally or locally (bind to another specific component).
var Child = Vue.extend({
// ...
})
var Parent = Vue.extend({
template: '...',
components: {
'my-component': Child
}
})
Thiw new component () will only be available inside the scope (template) of the Parent component.
Inline registration
You can extend and register a component in one step:
Vue.component('custom-component', {
template: '<div>A custom component!</div>'
})
Also when the component is registered locally:
var Parent = Vue.extend({
components: {
'custom-component': {
template: '<div>A custom component!</div>'
}
}
})
Data registration in components
Passing an object to the data property when registering a component would cause all instances ofthe component to point to the same data. To solve this, we need to return data from a function.
var CustomComponent = Vue.extend({
data: function () {
return { a: 1 }
}
})
Events
One of the ways components can communicate with its ancestors/descendants is via custom communication events. All Vue instances are also emitters and implement a custom event interface that facilitates communication within a component tree. We can use the following:
• $on: Listen to events emitted by this components ancestors or descendants.
• $broadcast: Emits an event that propagates downwards to all descendants.
•$dispatch: Emits an event that triggers first on the component itself and than propagates upwards to all ancestors.
• $emit: Triggers an event on self.
For example, we want to hide a specific button component inside a form component when the form submits. On the parent element:
var FormComponent = Vue.extend({
// ...
components: {
ButtonComponent
},
methods: {
onSubmit () {
this.$broadcast('submit-form')
}
}
})
On the child element:
var FormComponent = Vue.extend({
// ...
events: {
'submit-form': function () {
console.log('I should be hiding');
}
}
})
Some things to keep in mind:
•Whenever an event finds a component that is listening to it and gets triggered, it will stop propagating unless the function callback in this component returns true.
• $dispatch() always triggers first on the component that has emitted it.
•We can pass any number of arguments to the events handler. Doing this.$broadcast('submit-form', this.formData, this.formStatus) allows us to access this arguments like 'submit-form': function (formData, formStatus) {}