Tags are a useful and a little playful way to provide context for a record. I am building a simple application (using Vue 3 and Vuetify) where a group of friends shares tips on restaurants, places to stay and activities to undertake. I want such tips to be decorated with tags to make them better understood and easier found. However, I do not want to predefine all tag values in advance: the users are more than capable of defining their own tag values.
I was looking for a Vue or Vuetify component that allows users to assign tags from a predefined set as well as add tags of their own. The Vuetify autocomplete component with chips option did most of what I needed, except the ability to add one’s own tags. So I took the autocomplete and created my own component. This is what is looks like in action:
TagComponent to select from existing tags (violet and green) and add self defined tags (such as red and yellow). Note: keying in one or more characters will filter the tags; pressing Tab or Enter will automatically select and add the first tag matching the string
The component takes two properties: the list of predefined tags and the list of already selected tags. It emits an event whenever the list of selected tags changes .
The user can open the tag cloud to select tags from and can also key in characters to have the tags filtered. When the user presses Tab or Enter, the first tag matching the keyed in characters is added. If none matches, the keyed in value is added as new tag (and is also added to the list of selectable tags — see what happens with red in the demo).
You will find the code for the component in the live demo at the Vuetify Playground.
To use the component:
<template>
<v-app>
<v-container>
<TagComponent
:tags="mytags"
:theTags="myselectedTags"
@tagSelectionChanged="handleTagSelectionChanged"
>
</TagComponent>
</v-container>
</v-app>
</template>
<script setup>
import { ref } from 'vue'
import TagComponent from './TagComponent.vue'
const mytags = ref(['black', 'blue', 'green', 'violet', 'purple'])
const myselectedTags = ref(['blue'])
const handleTagSelectionChanged = e => {
myselectedTags.value = [...e]
}
</script>The function handleTagSelectionChanged() is triggered whenever the list of selected tags changes.
The code for the component is also in this GitHub Gist.