表示する方法
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>