LoginSignup
2
0

More than 3 years have passed since last update.

【Nuxt.js】v-forの一意なマーキングを使って削除ボタンを作る

Posted at

v-forで出現したコンポーネントを削除するボタンを実装する

まずは、それぞれの要素にマーキングし、削除ボタンも一意化する

template
<v-col cols="4" v-for="(feed, index) in feeds" :key="index">
  <v-card>
    <v-card-actions>
      <v-btn @click="deleteFeed(index)" icon>

RailsAPIに、削除リクエストを送る

script
methods: {
    async deleteFeed (index) {
      await this.$axios.$delete(`/api/v1/feeds/${this.feeds[index].id}`)
    }
  }

index番号から特定した、配列feedsの要素idを用いてリクエストを送る

data内の配列feedsの要素を削除する

script
  data () {
    return {
      feeds: [
        { id: 1, title: "東京中央銀行" },
        { id: 2, title: "東京セントラル証券" },
        { id: 3, title: "電脳雑伎集団" },
        { id: 4, title: "スパイラル株式会社" },
      ],
    }
  },
  methods: {
    async deleteFeed (index) {
      this.feeds.splice(index, 1)
    }
  }

配列番号indexを用いて、特定の配列feedsの要素を削除している。
spliceメソッドについてはこちら

最終的なソースコード

<template>
<v-col cols="4" v-for="(feed, index) in feeds" :key="index">
  <v-card>
    <v-card-actions>
      <v-btn @click="deleteFeed(index)" icon>
        <v-icon>mdi-close</v-icon>
      </v-btn>
    </v-card-actions>
  </v-card>
</v-col>
</template>
<script>
export default {
  data () {
    return {
      feeds: [
        { id: 1, title: "東京中央銀行" },
        { id: 2, title: "東京セントラル証券" },
        { id: 3, title: "電脳雑伎集団" },
        { id: 4, title: "スパイラル株式会社" },
      ],
    }
  },
  methods: {
    async deleteFeed (index) {
      console.log(`${index}:${this.feeds[index].id}`);
      const res7 = await this.$axios.$delete(`/api/v1/feeds/${this.feeds[index].id}`)
      this.feeds.splice(index, 1)
      return console.log(res7.status);
    }
  }
}
</script>

おまけ 一意なマーキングを要素のidにする

<v-col cols="4" v-for="feed in feeds" :key="feed.id">
  <v-card>
    <v-card-actions>
      <v-btn @click="deleteFeed(feed.id)" icon>
        <v-icon>mdi-close</v-icon>
      </v-btn>
    </v-card-actions>
  </v-card>
</v-col>

もう一つv-forのマーキングで、idキーで付与する場合もあるが、、、複雑で冗長化するだろう。。。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0