Vue.js Tip #4 Dead simple tag input component in 256 bytes

Marcos Neves
vuejs-tips
Published in
2 min readMar 6, 2017

A fancy tag editor can be very complex to implement, but this one do the job in less than 500 bytes!

If you want to use v-model with your custom component, you have to follow these rules:

  1. Data gets in with the value property
  2. and gets out as a input event.

Here's a template code that apply those rules. (unrelated code removed)

{
template: '<input v-model="editableValue">',
props: ['value'],
computed: {
editableValue: {
get () { return this.value }
set (newValue) { this.$emit('input', newValue) }
}
}
}

You can't bind the input v-model directly to value, cause it's readonly, that's why we need to create a computed property with custom getter and setter.

Our tag editor gets an Array of tags, convert it to an editable string and bind's it to the input. After each change, it converts it back to array and emits as a input event. Something like this:

{
template: '<input v-model="editableValue">',
props: ['value'],
computed: {
editableValue: {
get () { return this.value.join(' ') }
set (newValue) { this.$emit('input', newValue.split(' ')) }
}
}
}
final code

Sure it's not fancy as others tag editors out there, but it's so lite and easy to understand that pays the price, right?

--

--

Marcos Neves
vuejs-tips

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