A small Vue.js app
Displaying a list of tags from an array
So far, I have written a Vue.js app that:
- Displays its own title, which is stored as a string in its
data
object - Takes text as user input and stores it in its
data
object as a string - Takes tags as user input and stores them in its
data
object as an array of strings
Goal
Next, I want to display the list of tags in a useful way.
To do this, I need to iterate over the items in the tempTags
array, and the Vue directive v-for
exists for just this sort of job.
I’ll display two buttons for each item in the tempTags
array: one displaying the text of the tag, and one with an “x” on it. This sets up the template for later adding a method to remove tags, and/or to have another view or action triggered by clicking on a tag name.
In the Vue instance’s template
, I replace
<div id="tag-buttons-wrapper">
Current tag list: {{tempTags}}
</div>
with
<div id="tag-buttons-wrapper">
<div class="tag-buttons" v-for="tag in this.tempTags" v-bind:key="tag">
<button class="tag-lhs">{{tag}}</button>
<button class="tag-rhs"> x </button>
</div>
</div>
The v-for="tag in this.tempTags"
bit repeats the template element (a <div>
with class="tag-buttons"
) once for each item in the tempTags
array. It also gives the current iteration’s array item the name tag
. Whichever item the loop has reached in the array, the mustache interpolation {{tag}}
within the loop applies to the value of that item.
I also added v-bind:key="tag"
to the element.
The directive v-bind
binds an attribute (or a component prop) to the value of an expression, so that Vue can make it reactive to changes in that value.
The key
attribute is used to keep track of a specific item, regardless of whether its array index changes. It needs to be bound to a unique identifier to work.
As v-for
iterates through tempTags
, v-bind:key="tag"
binds the key
attribute of each item to its actual value (tag
). The tags themselves work as unique identifiers because I wrote the addNewTag(ev)
method to make sure there are no duplicates.
I could have left out v-bind:key="tag"
for the moment, because by default Vue tracks the items in a v-for
loop by their array indices. However, the unique item identifier leaves less room for mix-ups in situations where the indices may change, e.g. if a tag is deleted from somewhere in the middle of the array.
Note that there is a shorthand for v-bind:
, and it would work just as well to write :key
instead of v-bind:key
.
I’ve used some CSS to style the buttons, displaying each tag’s buttons side-by-side and turning the “x” button red when clicked. This particular button will gain its functionality in the next step.