Vue勉強中にaxios というライブラリが出てきたので、調べた。
HTTP通信(データの更新・取得)を簡単に行うことができる、JavaScriptのライブラリ。
とのこと。
Vueを使うのに必須という訳ではなく、Vueとは無関係に、このライブラリ単体で使えるものらしい。
axios には、get
以外にも delete
, post
, put
と言った関数があるようだ。
(Vue.js 3.1.5を使用)
javascript
const app = Vue.createApp({
data: () => ({
users: []
}),
mounted: function() {
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => this.users = response.data)
.catch(error => console.log(error))
},
})
app.mount('#app')
mounted
は、ライフサイクルフックの1つで、Viewインスタンスがマウントされたときに呼ばれる。
axios.get(url)
で、urlからデータを取得することができる。
成功した場合は、then()
の中にレスポンスが返ってくる。
レスポンスは以下のような中身になっているので、
レスポンス
{
// サーバーから提供されたレスポンス
data: {},
// サーバーのレスポンスに含まれる HTTP ステータスコード
status: 200,
// サーバーのレスポンスに含まれる HTTP ステータスメッセージ
statusText: 'OK',
// サーバーが応答した HTTP ヘッダー
// ヘッダー名はすべて小文字で、ブラケット記法でアクセスできます。
// 例: `response.headers['content-type']`
headers: {},
// リクエストの際に `axios` に提供された設定
config: {},
// このレスポンスを生成したリクエスト
request: {}
}
ので、response.data
とすることで、データの内容を取得することができる。
URLの、https://jsonplaceholder.typicode.com/users から返ってくるデータの内容は、
以下の形式になっていて、
データ
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
(以下略。複数人続く・・・。)
HTMLで、このデータのうち、name
、email
、company.name
を表示するようにすると、
html
<body>
<div id="app">
<ul v-for="user in users">
<li >{{ user.name }}</li>
<li>{{ user.email }}</li>
<li>{{ user.company.name }}</li>
</ul>
</div>
</body>
以下のように表示された。