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!

Remember you can read this tip online (with copy/pasteable code), and don’t forget to share VueDose with your colleagues, so they also know about these tips as well!

See you next week.

Alex

Start saving time and get a tip about the Vue ecosystem every week, right in your inbox.

    Latest Vue Jobs