Subcomponents
This guide explains how to add other components to an instance.
Adding components
There are times a component needs to instantiate another component within itself. These nested components are often referred to as "subcomponents". Use the components options to accomplish this.
// subcomponent
const Topping = defineComponent({
state: {
type: {
type: String,
default: 'sprinkles',
},
},
render: {
$root() {
return this.$state.type;
},
},
});
// parent component
const FrozenYogurt = defineComponent({
components: {
topping() {
return {
constructor: Topping,
root: this.$root,
};
},
},
});
Updating a subcomponent
Use the state
property to define or control the state of the subcomponent. If values from this.$state
are applied directly to the subcomponent state, the states will be bound. This means that when the state of the parent changes, the corresponding state of the subcomponent will also change.
const FrozenYogurt = defineComponent({
state: {
topping: {
type: String,
default: 'Chocolate Syrup',
},
},
components: {
topping() {
return {
constructor: Topping,
root: this.$root,
state: {
type: this.$state.topping, // <-- binds the states
},
};
},
},
});
Subscribing to subcomponents
There are times it may be necessary to update the state of the parent component when the state of the subcomponent has changed. To accomplish this, add an entry to the subcomponent's subscribe
option. Each key in this object must be the name of the state property to subscribe to, while the corresponding value is a function that is called when the value changes.
const FrozenYogurt = defineComponent({
state: {
topping: {
type: String,
default: 'Chocolate Syrup',
},
},
components: {
topping() {
return {
constructor: Topping,
root: this.$root,
state: { type: this.$state.topping },
subscribe: {
type: (value) => {
this.$state.topping = value; // <-- update the parent
},
},
};
},
},
});