[Vuejs]-How can I use chips like a tag sorter in Vue?

1๐Ÿ‘

โœ…

If I understood you correctly, try like following snippet:

const app = Vue.createApp({
  data() {
    return {
      images: [{tags: ["art"], url: "https://picsum.photos/50", name: "my image name",}, {tags: ["chipmunk", "art"], url: "https://picsum.photos/51", name: "my image name",}, {tags: ["ship"], url: "https://picsum.photos/49", name: "my image name",}, {tags: ["art", "ship"], url: "https://picsum.photos/48", name: "my image name",},],
      tags: [],
      selected: []
    }
  },
  mounted() {
    const set = new Set([])
    this.images.forEach(i => set.add(...i.tags))
    this.tags = [...set]
  },
  computed: {
    getItems() {
      if(this.selected.length) {
        return this.images.filter(i => {
          return this.selected.every(s => i.tags.includes(s) )
        })
      }
      return this.images 
    }
  },
  methods: {
    selectTag(tag) {
      this.selected = !this.selected.includes(tag) ? [...this.selected, tag] : this.selected.filter(s => s !== tag)
    }
  }
})
app.mount('#demo')
.tags, .container {
  display: flex;
  column-gap: 1em;
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div class="container">
    <template class="" v-for="tag in tags">
      <button @click="selectTag(tag)">{{ tag }}</button>
    </template>
  </div>
  <div class="tags" v-if="selected.length">
    <template v-for="sel in selected">
      <p>{{ sel }}</p>
    </template>
  </div>
  <div class="tags">
    <div v-for="img in getItems">
      <p>{{ img.name }}</p>
      <img :src="img.url" />
      <p>{{ img.tags }}</p>
    </div>
  </div>
</div>

Leave a comment