Vue.js 2.6 – slots
Today I started the updating of my book, Manual do Vue.js (https://leanpub.com/manual-vuejs), to the most recent version of Vue, the 2.6 version.
I began by revisiting the medium article of Evan You about this new version. It can be found here: https://medium.com/the-vue-point/vue-2-6-released-66aa6c8e785e.
Evan starts his article with slots and so do we (btw, a small clarification: Even refers only scoped slots, but in fact, the change is a little bit more general, affecting also named slots). They now have a different syntax. Before we see an example, just a reminder that slots are a technic used to give more flexibility to our components. With normal components, we use props to pass data to the component. With slots, we pass not only data but a specific portion of the template (for sure, slots can also be used to pass data, but that doesn’t seem to be their best use).
A good case is a table. How each row will be formatted? With slots, the component will receive the data for the rows via a prop, but the template for rows will be given via… well, via the slots syntax, which, as mentioned, has now changed.
A very detailed discussion of the changes and their rationale can be found at https://github.com/vuejs/rfcs/blob/master/active-rfcs/0001-new-slot-syntax.md. It is a very interesting reading.
But the point to retain now is that the syntax as changed only when using a component with slots, not when writing one. So, if you are writing a library, nothing as changed. But, when using the library, you will change the code.
Was it clear? Just to make sure: if we think of a child component (the one with the slot) and a parent component (the one who uses the child component), then the child component stays the same, but the parent will change! OK, let’s go on.
We can divide slots into three types: simple, named and scoped. Let’s see each of them.
For a simple first example, we will have a “Post” component, with a title and a body. “title” will be a prop, but the “body” will be passed via a slot so that we can freely write HTML on it.
So, what has changed…? Nothing, really! Because, in this particular example, we are using just a simple slot, not a named one or a sloped scope. And, for simple slots, the syntax is the same.
Let’s change the example. The “Post” component will now have a name slot.
Now we have a change. We have to use the <template> element and a brand new v-slot directive, in which the modifier is the name of the specific slot.
Let’s check a final example with a scoped slot.
Will we have a PostList component, to list the posts. This component’s template is an html table, but we want the row content and template to be flexible.