![見出し画像](https://assets.st-note.com/production/uploads/images/82899239/rectangle_large_type_2_20b7e97ffea0fcbf1e23079bf7dc2dc8.png?width=1200)
JavaScript! - Vue.js -使い方の基本。2
少し整理ができたところでもう少し詳しい使い方を以下サイトを参考にさせてもらい実行してみます。
webAPIを利用しデータを取得したいと思います。
CDNを追加します。
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
これで、 "axios"という非同期でデータを取得してくることができる便利モジュールを使うためのCDNです。これで簡単に外部サイトで提供されている"Json"を変換してデータを取り出せるようにします。
データを取得して、そのデータを表示できるようにHTMLを用意します。
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Website</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>{{ user.website }}</td>
</tr>
</tbody>
</table>
ループを使ってデータ(users)を取得して、
<tr v-for="user in users" :key="user.id">
その取得したものを、テーブルのセルにあたる
<td>{{ user.name }}</td>
のように入れていきます。
あとはJavaScript、Vueの命令を作ります。
<script>
Vue.createApp({
setup() {
const message = Vue.ref("Hello World");
const users = Vue.ref([]);
Vue.onMounted(() => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((response) => (users.value = response.data));
});
return {
message,
users,
};
},
}).mount("#app");
</script>
HTMLで使っているものを利用するには
const message = Vue.ref("Hello World");
const users = Vue.ref([]);
Vue.ref
を使って変数宣言します。
Jsonを取得するには以下、
Vue.onMounted(() => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((response) => (users.value = response.data));
});
Vue.onMounted(()
を使って、CDNを使って取り込んだ"axios"を使います。
https://jsonplaceholder.typicode.com/users
のサイトはダミーのJsonを発行してくれる便利サイトです。
.then((response) => (users.value = response.data));
データはusers.valueに入っていくのであとは、
return {
message,
users,
};
で"users"に取得したデータを返して、HTMLで使います。あとは
<tr v-for="user in users" :key="user.id">
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>{{ user.website }}</td>
</tr>
に反映されて取得したデータを表示します。
![](https://assets.st-note.com/img/1658178147930-FrRxDdj92h.png?width=1200)
無事に表示されました。axiosを必ずCDNで取得しておかないとJsonをとってこれないので注意。
この記事が気に入ったらサポートをしてみませんか?