0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Vue]axiosでdelete後に非同期にdataを更新する

Posted at

何がしたかったか

Vueにおいて、axiosのgetでdataをとってきて配列でitemを管理している時に、
axiosのdeleteでDB側のデータを削除した際、フロント側も非同期に更新されるようにしたかった。
(v-forなどでとってきた配列データをリスト形式で並べているような想定です。)

↓イメージ
ezgif.com-gif-maker.gif

※もっといい解決方法やそもそもその認識間違ってない?そもそもそんな問題発生しなくない?などのご指摘などありましたらコメントしていただけると幸いです。

やったこと

最初、vue側のページを再レンダリングすればもう一回axiosのgetでデータをとってきてくれるかと思ったが、Vueの公式ページ

もし Vue で強制更新をする必要な場面に遭遇する場合、99.99% のケースであなたは何かを間違えています。
と書いてあったため別の方法で更新されるようにした。

※Vueの強制再レンダリングの方法を知りたい方はこちら

解決方法

deleteが成功したタイミングでvueで管理しているdataから削除したアイテムを削除する。
ここで、vueで非同期にdataを更新させるためには、配列からその要素を削除すれば良いが、そのときはsplice()を使う。

<配列>.splice(<始まりのインデックス>, <削除する要素数>)

のように使用するので、削除する関数にindexも渡しておく。
サンプルコード

<script>
import axios from "axios";
export default {
  data: () => ({
    tasks: [],
  }),
  mounted() {
    axios
      .get(
        "/get"
      )
      .then((response) => (this.tasks = response.data))
      .catch((error) => console.log(error));
  },
  methods: {
    deleteTasks(id,index) {
      axios
        .delete("/delete/" + id)
        .then(() => {
          console.log("削除成功");
          this.tasks.splice(index, 1); // ここ。
        })
        .catch(() => {
          console.log("失敗");
        });
    },
  },
};
</script>

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?