Vue
Vueのaxiosのgetとpostの基本的な書き方
いつもご利用ありがとうございます。
この記事には広告が掲載されており、その広告費によって運営しています。
オススメ本
まず、この記事の趣旨としては、世の中にはいろんな Vue、axios の記事があると思うんですが、その中でも最もシンプルな例を分かりやすく書こうと思いました。
色々な書き方がある中で一番よく見かける形のものを紹介していきます。
基本的な書き方 GET
GET はこのような書き方
.vue ファイル
<template>
<div>
<div v-for="post in posts">
<p>{{post.title}}</p>
<p>{{post.content}}</p>
</div>
</div>
<template>
<script>
export default {
data() {
return {
posts: [],
}
},
created() {
this.test()
},
methods: {
test: function () {
axios
.get("/test")
.then(res => {
console.log(res)
this.posts = res.data.posts
})
.catch(err => {
console.log(err)
})
},
},
}
</script></template
></template
>
基本的な書き方 POST
<template>
<div>
<input v-model="title" />
<textarea v-model="content"></textarea>
<button type="button" @click="test">送信</button>
</div>
</template>
<script>
export default {
data() {
return {
title: "",
content: "",
}
},
methods: {
test: function () {
axios
.post("/test", {
title: this.title,
content: this.title,
})
.then(res => {
console.log(res)
this.posts = res.data.posts
})
.catch(err => {
console.log(err)
})
},
},
}
</script>