Vue.js — v-bind directives & slots wrapper component tricks

Best wait to componentize a existing component (doing a wrapper of a existing component)

Christian Marinelli
4 min readApr 28, 2021

When importing external libraries like bootstrap-vue or vuetify into our vue project, we get multiple default components. Many of these components have all the functionalities that we need but sometimes we want to add specific functionalities for our needs (in short, enhance the components), to solve this we will create a component that wraps the component that already exists with new functionalities.

Creating a wrapper component is simple but it becomes tedious when we must pass all or almost all the properties already defined to the component that we are going to wrap

I’m going to make a wrapper named MultiSelect for the Select component (v-select) that belongs to the vuetify library

I’m going to add a spinner to my MultiSelect component since vuetify v-select component doesn’t have one.

Now comes the tedious part: the wrapper component (MultiSelect) must receive all or almost all the props defined in the Select component (v-select) and then pass them on.

It would be something like this

If we continue adding each props that the v-select component needs to the MultiSelect component, this makes the component tedious and uncomfortable to use. Adding 3 or 4 more props is not a big deal but when we are wrapping component with more than 30 props with in the case of v-select, it is a headache.

Solution Props— I will teach you the easiest and most practical solution

Doing a spread operator of the props and attrs that are received in the MultiSelect component directly to the v-select component

Here's the magic: v-bind=”{ …$attrs, …$props }”

The same problem with props happens with slots. We would have to specify each slot needed by the component that we are wrapping in our case the v-select component

It would be something like this

Registering all the necessary slots makes the component tedious to use and adds many lines of non-relevant code. Adding 3 or 4 more slots is not a big deal but when we are wrapping component with more than 7 slots with in the case of v-select, it is a headache.

Solution Slots— I will teach you the easiest and most practical solution

  1. We declare a variable called slots which will have a default value of an empty array. The purpose of this variable is to save all the names of the slots that were passed to the component.
  2. On the mounted, this function Object.keys (this. $ ScopedSlots) is executed, this function returns all the names of the slots that were passed.
  3. We make a v-for of each name that is in the variable slots inside the component wrapped (v-select)

--

--