Vue.js Tip #5 Tag list component
Published in
2 min readMar 7, 2017
Following last tip, we are going to create a component to list tags.
We learned that a component to supports v-model, needs 2 things: get data through value property and emit changed data with a input event.
Our tag list component, get an array of tags that can be deleted, iterates over it rendering the label and a remove button. The remove method, first clone the original Array (arrays in javascript are references), removes the index and emit this new changed array.
{
template: `<div>
<span v-for="tag, index in value">
{{tag}}
<button @click="remove(index)">x</button>
</span>
</div>`,
props: ['value'], // Array of tags
methods: {
remove (index) {
var clonedValue = this.value.slice()
clonedValue.splice(index, 1)
this.$emit('input', clonedValue)
}
}
}
Things to remember
- v-model injects data into value property and expect a input event with the new one.
- Use
Array.slice()
to clone a Array. - Use
Array.splice(index, 1)
to remove a item from the Array, or this.$delete(array, index) new in Vue 2.2.