vue中比较完美请求的栗子(使用 axios 访问 API)

本文提供了一个在Vue中利用Axios库优雅地进行API调用的完整示例,展示了如何处理加载状态、错误情况及数据展示。通过获取实时比特币价格指数,演示了异步请求的最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue中比较完美请求的栗子(使用 axios 访问 API)

官网地址:https://vuejs.bootcss.com/v2/cookbook/using-axios-to-consume-apis.html

实例:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <title>Document</title>
</head>

<body>
    <div id="app">
        <h1>Bitcoin Price Index</h1>

        <section v-if="errored">
            <p>We're sorry, we're not able to retrieve this information at the moment, please try back later</p>
        </section>

        <section v-else>
            <div v-if="loading">Loading...</div>

            <div v-else v-for="currency in info" class="currency">
                {{ currency.description }}:
                <span class="lighten">
                    <span v-html="currency.symbol"></span>{{ currency.rate_float | currencydecimal }}
                </span>
            </div>

        </section>
    </div>
    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    info: null,
                    loading: true,
                    errored: false
                }
            },
            filters: {
                currencydecimal(value) {
                    return value.toFixed(2)
                }
            },
            mounted() {
                axios
                    .get('https://api.coindesk.com/v1/bpi/currentprice.json')
                    .then(response => {
                        this.info = response.data.bpi
                    })
                    .catch(error => {
                        console.log(error)
                        this.errored = true
                    })
                    .finally(() => this.loading = false)
            }
        })
    </script>

</body>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值