0
0

Vue勉強中にaxiosというAPIが出てきて調べている際に(前回の記事)、
axiosに似たAPIにfetchというものがあるとわかった。

比較してる記事がいくつかありました。

✅axiosはfetchを進化させたようなライブラリ。

ざっくり解説「シンプルにHTTPリクエストができるfetchが進化したライブラリ」

とのこと。

確かに、fetchの方が長く、axiosのほうが簡潔なコードになるようだ。

前回の、axios のコード

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')

これを、fetchで書くと、こうなった。

javascript
const app = Vue.createApp({
    data: () => ({
        users: []
    }),
    mounted: function() {   
        fetch('https://jsonplaceholder.typicode.com/users')
          .then(response => {
                if (!response.ok) {
                throw new Error('Network response was not ok');
                }
                return(response.json());
          })
          .then(data => this.users = data)
          .catch(error => console.log(error));
    },
})

app.mount('#app')

axiosだと、then()は1個でいいけど、fetchは2個書かなきゃいけない。
1個目のthen()の中でエラー処理したり、json()で、jsonに変換したりとかしないといけない。
こういう部分が、axiosの方が簡潔、という話らしい。

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>

画面表示結果は、前回と同じ。

6.PNG

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0