Adaptive components using v-bind and v-on
When you're working with component-based technologies, as soon as an application starts to grow, you need to structure and categorise your components in order to keep them as simple and maintainable as possible.
Component composition it's a powerful pattern popular that helps reusing and structuring code in component-based technologies... But what the heck is component composition? Although being a generic concept, let's say that when you do component composition you're creating a component by the combination of one or more.
One case could be when we have a base component, say BaseList
, and you want to create a similar component with some additional functionality on top of it, like SortableList
. I call them Adaptive Components (also proxy or wrapper components).
When building an Adaptive Component, you usually want SortableList
to keep the same API that the original BaseList
in order to keep the components consistent. Which means that from SortableList
you need to pass down all the props and listen to all events of BaseList
.
Here's the trick: you can do that by using v-bind
and v-on
:
<!-- SortableList -->
<template>
<AppList v-bind="$props" v-on="$listeners"> <!-- ... --> </AppList>
</template>
<script>
import AppList from "./AppList";
export default {
props: AppList.props,
components: {
AppList
}
};
</script>
The way v-bind
works is basically the same than passing one by one all the properties to AppList
, but instead passed all at once in an object. $props
is the object in the component instance that contains all the properties of that component.
As you can imagine, v-on="$listeners"
works exactly the same way, but for events.
This would work for two-way bound components using v-model
as well. In case you didn't know, v-model
is a shorthand for passing a value
property and listening to a input
event.
Finally, remember that in Vue.js we have to explicitly declare the props of a component in order to be interpreted as such. A quick way to do that when building an Adaptive Component is to use the base component props to define them, like I do in props: AppList.props
.
That's it! Maybe you didn't see the practical use of the Adaptive Components? No worries, in the next tip I'll build a real case of an Adaptive Component so you can see it in action. Stay tuned!
Related Articles
The new Provide and Inject in Vue 3
Getting stuck into the prop drilling? Learn how provide/inject can make your components more flexible and independent in this short tutorial.
Jul 18, 2022
Sep 24, 2019
Using Scoped Slots in Vue.js
Quick example on how to use scoped slots for component reusability in vuejs
Sep 15, 2019
Sponsors
VueDose is proudly supported by its sponsors. If you enjoy it, consider supporting it to ensure the project maintainability.