Vue.js Tip #5 Tag list component

Marcos Neves
vuejs-tips
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)
}
}
}
final code

Things to remember

  1. v-model injects data into value property and expect a input event with the new one.
  2. Use Array.slice()to clone a Array.
  3. Use Array.splice(index, 1) to remove a item from the Array, or this.$delete(array, index) new in Vue 2.2.

--

--

Marcos Neves
vuejs-tips

Ancient Brazilian web developer, from php, through Rails to Javascript, Vue.js enthusiast to React.