Vue.js grid | Scoped Slots in Vue.js Components

The mechanism of slots in Vue.js makes it easier to create universal, reusable components. Slots are very powerful and at first may seem hard to use, especially the more advanced variants. In this article, I will present a reusable grid component using scoped slots with dynamic names, but to make it easier to understand, I will start with some simpler examples.

Default slot

If you’re using Vue.js, you probably already know the simplest kind of slot — the default slot:

<template>
  <button type="submit">
    <slot/>
  </button>
<template>

Such slot is simply a placeholder for the component’s content. This component can be used like this:

<SubmitButton>Submit</SubmitButton>

In this simple example, we could just use a text property instead of a slot. However, the content of a button can be more than just plain text — it might contain any HTML markup, for example an icon or image, or even a nested Vue.js component.

Also, using a slot more closely resembles the standard HTML <button> tag, so such code is easier to write and understand.

Scoped slot

One of most common use of a scoped slot is when a component is used to render an array of items, and we want to be able to customize the way each item is rendered.

The simplest example is an unordered list:

<template>
  <ul>
    <li v-for="( item, index ) in items" :key="index">
      <slot :item="item">{{ item }}</slot>
    </li>
  </ul>
</template>
<script>
export default {
  props: {
    items: { type: Array, required: true }
  }
}
</script>

You can see that the slot has an item property, which represents the currently rendered item. As you will later see, a scoped slot can contain as many properties as you need.

The slot also has fallback content, which simply displays each item as plain text. So in its simplest form, this component can be used to render an array of strings:

<SimpleList :items="[ 'Tom', 'Felix', 'Sylvester' ]"/>

However, the component can be customized to display an array of more complex objects. Consider the following example:

<template>
  <SimpleList :items="cats">
    <template v-slot="{ item: cat }">
      {{ cat.name }}, {{ cat.age }} years old
    </template>
  </SimpleList>
</template>
<script>
export default {
  data() {
    return {
      cats: [
        { name: 'Tom', age: 3 },
        { name: 'Felix', age: 5 },
        { name: 'Sylvester', age: 7 }
      ]
    };
  }
}
</script>

As you can see, the parent component can retrieve the value of the item property using the special v-slot directive. We can even rename the property to make the code more readable — in our example, we can access the current item using the cat variable. This works just like object destructuring, where you can assign object properties to variables and optionally rename them.

Note that using a <template> element isn’t necessary if you have just one default slot. So the above code could be written like this:

<template>
  <SimpleList :items="cats" v-slot="{ item: cat }">
    {{ cat.name }}, {{ cat.age }} years old
  </SimpleList>
</template>

Grid component — simple version

What if we want to display the above data as a table? We could use a similar approach and use a default scoped slot:

<template>
  <table>
    <thead>
      <tr>
        <th v-for="( column, prop ) in columns" :key="prop">
          {{ column }}
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="( row, index ) in rows" :key="index">
        <td v-for="( _, prop ) in columns" :key="prop">
          <slot :row="row" :prop="prop">
            {{ row[ prop ] }}
          </slot>
        </td>
      </tr>
    </tbody>
  </table>
</template>
<script>
export default {
  props: {
    columns: { type: Object, required: true },
    rows: { type: Array, required: true }
  }
}
</script>

The columns property of the grid component is an object which maps column names to their header text. The rows property is an array of objects representing the rows of the table.

You can see that the body of the table contains two nested v-for loops. The outer loop iterates over the elements of the rows array, and the inner v-for loop iterates over the properties of the columns object.

The scoped slot now has two properties, row which represents the current row, and prop which represents the name of the current column. The default content simply extracts the value from the row and displays it as plain text.

In the simplest case, this component can be used like this:

<template>
  <SimpleGrid :columns="columns" :rows="cats"/>
</template>
<script>
export default {
  data() {
    return {
      cats: [
        { name: 'Tom', age: 3 },
        { name: 'Felix', age: 5 },
        { name: 'Sylvester', age: 7 }
      ]
    };
  },
  computed: {
    columns() {
      return { name: 'Name', age: 'Age' };
    }
  }
}
</script>

Because the grid component uses a slot, we can customize the way the individual cells are rendered. In a typical grid component, different columns are rendered in different ways, depending on their type. To demonstrate this, let’s add a third column which displays images instead of text:

<template>
  <SimpleGrid :rows="cats">
    <template v-slot="{ row: cat, prop }">
      <img v-if="prop == 'image'" :src="cat.image">
    </template>
  </SimpleGrid>
</template>
<script>
export default {
  data() {
    return {
      cats: [
        { name: 'Tom', age: 3, image: 'tom.jpg' },
        { name: 'Felix', age: 5, image: 'felix.jpg' },
        { name: 'Sylvester', age: 7, image: 'sylvester.jpg' }
      ]
    };
  },
  computed: {
    columns() {
      return { name: 'Name', age: 'Age', image: 'Image' };
    }
  }
}
</script>

Note that our slot template contains conditional code that checks the name of the current column, represented by the prop variable. The <img> tag is only rendered for the image column, otherwise the template will not render anything and the fallback content will be used.

This works fine in this simple example, but if there are many different columns, this code can become hard to read and ineficient. For example, if we want to also customize the age column, we would have to write the following code:

<template>
  <SimpleGrid :rows="cats">
    <template v-slot="{ row: cat, prop }">
      <template v-if="prop == 'age'">
        {{ cat.age }} years old
      </template>
      <img v-else-if="prop == 'image'" :src="cat.image">
    </template>
  </SimpleGrid>
</template>

As the grid becomes more complex, we have to add more v-else-if directives, which is not a very elegant solution.

Named slots

So far we’ve been using a default slot, but aVue.js component can contain multiple slots with different names. For example, a page layout component could contain a default slot for the page content and named slots for the header and footer:

<template>
  <div class="header">
    <slot name="header"/>
  </div>
  <slot/>
  <div class="footer">
    <slot name="footer"/>
  </div>
</template>

However, the names of slots don’t have to be hard-coded. We can use dynamic slot names using the v-bind:name syntax or the abbreviated :name syntax. This can be very useful for creating a better version of our grid component.

Grid component using named slots

Let’s modify the grid in the following way:

<template>
  <table>
    <thead>
      <tr>
        <th v-for="( column, prop ) in columns" :key="prop">
          {{ column }}
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="( row, index ) in rows" :key="index">
        <td v-for="( _, prop ) in columns" :key="prop">
          <slot :name="'cell-' + prop" :row="row">
            {{ row[ prop ] }}
          </slot>
        </td>
      </tr>
    </tbody>
  </table>
</template>
<script>
export default {
  props: {
    columns: { type: Object, required: true },
    rows: { type: Array, required: true }
  }
}
</script>

The only change is the highlighted line. As you can see, the slot is no longer a default slot; it’s a named slot with a dynamic name which depends on the name of the columns. So in our example, the component has three slots, named cell-name, cell-age and cell-image.

The parent component can use these named slots in the following way:

<template>
  <SimpleGrid :columns="columns" :rows="cats">
    <template v-slot:cell-age="{ row: cat }">
      {{ cat.age }} years old
    </template>
    <template v-slot:cell-image="{ row: cat }">
      <img :src="cat.image">
    </template>
  </SimpleGrid>
</template>
<script>
export default {
  // same as before
}
</script>

Two custom templates are defined for the cell-age and cell-image slots, and the first column will display the fallback content.

The code becomes more elegant and easier to understand, because you can immediately see which template is associated with each column and no conditional directives are necessary.

This technique can be used to add another small improvement to our grid component — we can wrap column headers in a dynamically named slot:

<thead>
  <tr>
    <th v-for="( column, prop ) in columns" :key="prop">
      <slot :name="'header-' + prop">
        {{ column }}
      </slot>
    </th>
  </tr>
</thead>

Now, there are three additional named slots, header-name, header-age and header-image, which can be used to replace the content of the individual column headers, for example to add filters or sort links.

Final notes

Note that all these code examples use the new syntax of slots which was introduced in version 2.6 of Vue.js. In older versions such elegant solution wouldn’t be possible, so this is a big and often underestimated improvement.

You can use the shorthand syntax and replace the v-slot prefix with the # symbol, though I personally prefer to use the more verbose version. Perhaps it’s just a matter of getting used to the new syntax.

Slots are one of the most complex features of Vue.js and learning to fully take advantage of them may take some time, but it’s definitely worth the effort. You can find many other useful examples in the official Vue.js documentation and also in the RFC document in which the new syntax was proposed.

#vuejs #javascript

Vue.js grid  | Scoped Slots in Vue.js Components
2 Likes37.95 GEEK