1
0

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.js】axiosで受け取ったエラーメッセージを表示する

Posted at

表示する方法

errorsという空のデータオブジェクトを用意して、そこにaxiosで受け取ったエラーを格納して表示します。

実際のコード

sample.vue
<template>
    <div class="sample">
        <!-- 複数のエラーもv-forで表示する -->
        <p class="error" v-for="error in errors" :key="error.id">{{ error[0] }}</p>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                keyword: '',
                baths: {},
                errors: {} // 空のオブジェクトを用意
            }
        },
        methods: {
            searchBath() {
                const url = '/post/search';
                this.errors = ''; // 描画する度にエラーを空にする
                axios.post(url, {
                    keyword: this.keyword,
                })
                .then(response => {
                    this.baths = response.data;
                })
                // 以下、エラーメッセージの受け取り
                .catch(e => {
                    this.errors = e.response.data.errors;
                })
            },
        }
    }
</script>
1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?