
Member-only story
Simple Vue.js grid using named scoped slots
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…