フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

Vueでタグを入力および削除できるコンポーネントを作成する

はじめに

  • 下記のようなタグ入力フォームを作る

コンポーネント作成

  • components/TagInput.vue ファイルを作成する
<template>
  <div class="current-user-tag-wrapper">
    <v-chip class="current-user-tag-chip"" v-for="(tag, index) in newTags" :key="index" close @click:close="removeTag(index)">
      {{ tag }}
    </v-chip>
    <v-text-field
      v-model="newTag"
      @keydown.enter="addTag"
      label="タグを入力してください"
    ></v-text-field>
  </div>
</template>

<script>
export default {
  data() {
    return {
      newTags: [],
      newTag: "",
    };
  },
  methods: {  
    addTag() {
      if (this.newTag.trim() !== "") {
        this.newTags.push(this.newTag.trim());
        this.newTag = "";
      }
      this.$emit('changeTags',this.newTags)
    },
    removeTag(index) {
      this.newTags.splice(index, 1);
      this.tags = this.newTags
      this.$emit('changeTags', this.newTags)
    },    
  },
};
</script>
<style>
※Vutifyを利用しております
</style>

コンポーネントの呼び出し

  • pages/sample.vueファイルに下記のように記述する
<template>
        (省略)
       <TagInput @changeTags="receiveTags"/>
   (省略)
</template>

<script>
<script>
import TagInput from '@/components/TagInput.vue'

export default {
  data() {
      // https://github.com/apertureless/vue-chartjs/issues/17
      return {
        tags: '',
      }
  },
  methods: {
    receiveTags(tags){
      this.tags = tags
    },
  }
}
</script>