-
Notifications
You must be signed in to change notification settings - Fork 6
Iterators Demo
In application development we spend a great deal of time creating lists: Posts, files, messages, pictures, todos, products...you name it: one template repeated for every item we want to display. Sure you can simply write a for
loop in your application every time you need to repeat a template, but as we learned with composite components, there are often very good reasons to abstract iterators into components. Here are the first six I could think of:
- You need virtualization for long lists
- You need pagination for long lists
- You need a way to select a single item in a list
- You need a way to select multiple items in a list
- You need a way to select multiple items in a list with a keyboard
- You need an accessible way to indicate which items are currently selected
So if we need to create an iterator, let's see how well Vue lets us do that. npm run scaffold List
Our list isn't just responsible for rendering a template over and over, it also controls the data that is passed into each item in the list. So we know that we'll have a prop to pass that data
in.
export default {
props: ['data']
};
All iterators need some sort of loop, and Vue provides us with a very nice one in v-for
. We'll make our list an unordered list, so our li
will contain all of the looping logic.
<li
v-for="item in data"
:key="item.id"
>
v-for
will loop through the data
array and for each item
in that array it will render <li :key="item.id
>` along with anything inside that tag.
Knowing that our todo list will be...a list of todos, we could drop our TodoItem into the <li>
and be done with it. But that obviously changes this from a List
component to a TodoItemList
component, which is far less useful. So how do we create a general purpose List component? The answer is Slots.
Slots are like little templates inside of our template. They provide a "slot" to put markup into, and specify what data is available to that markup. A template can have many slots (think header, body, footer), and they don't need to be used in a for loops, but when they are, they become really powerful!
<slot name="item" :item="item" />
The syntax is pretty straight forward. We name our slot whatever we like so we can reference it later, and then we pass in the item
so that whatever markup we place in the slot will have access.