【Vue.js】axiosで受け取ったエラーメッセージを表示する
表示する方法
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>
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>
Author And Source
この問題について(【Vue.js】axiosで受け取ったエラーメッセージを表示する), 我々は、より多くの情報をここで見つけました https://qiita.com/baby-0105/items/f65f31fff66e766116da著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .