首页 > 解决方案 > 如何仅在数据之前加载微调器

问题描述

我试图让我的Spinner组件仅在加载 API 数据之前显示,否则,它应该被隐藏。我创建了一个名为的变量value并将其设置为每当获取 API 信息时,但在使用and指令true时我似乎弄错了。目前,使用.v-ifv-elsev-if

我究竟做错了什么?

我是 Vue.js 的新手,我已经看到了该指令,v-cloak但我不太确定如何使用它。

<template lang="">
    <div>
        <Header />
        <Spinner v-if="!value" />
        <CryptoList v-else v-bind:crypts="cryptoData" />
    </div>
</template>
<script>
    import Header from "./components/Header";
    import CryptoList from "./components/CryptoList";
    import Spinner from "./components/Spinner";
    import axios from "axios";
    const API_KEY = "ed599676c60cb5b0b369519d8cadaa8a";

    export default {
        data: function() {
            return {
                cryptoData: [],
                value: null
            };
        },
        name: "App",
        components: {
            Header,
            CryptoList,
            Spinner
        },
        methods: {
            isMounted() {
                return (this.value = false);
            }
        },
        mounted() {
            axios
                .get(`https://api.nomics.com/v1/currencies/ticker?key=${API_KEY}`, {
                    params: {
                        "per-page": "100",
                        "page": 1,
                        "rank": 1
                    }
                })
                .then((response) => {
                    this.cryptoData = response.data;
                    console.log(response.data);
                })
                .catch(function(error) {
                    console.log(error);
                });

            this.value = true;
            console.log(this.value);
        }
    };
</script>
<style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-size: 16px;
    }
    body {
        font-family: "Baloo 2";
        font-weight: lighter;
        color: #e7e7de;
        background-image: url("./img/background.jpg");
        background-repeat: no-repeat;
        background-attachment: fixed;
    }
</style>

标签: javascriptvue.js

解决方案


您在API 调用返回this.value = true 之前进行设置。你必须这样做之后:

mounted() {
  axios
   .get(...)
     .then((response) => {
        this.cryptoData = response.data;
        // <= here the API call returned (you're inside the promise)
        this.value = true;
     });
  // <= here API call has not returned yet. (you're outside the promise)
  //    you're in mounted, right after the API call was made
}

另一种方法是根据' 的长度的当前值value转换为computed返回:true/falsecryptoData

data: () => ({
   cryptoData: []
}),
computed: {
  value() {
    return !!this.cryptoData.length;
  }
},
mounted() {
  axios
    .get(...)
       .then((response) => {
         this.cryptoData = response.data;
       });
}

每当您想再次显示微调器时,您所要做的就是清空cryptoData

this.cryptoData = [];

我还建议您进行命名实践(作为一般规则,命名变量或属性value, what, when, who, some, few, 被认为是不好的做法)。良好的做法是使用描述性名称,宣布所执行的角色或功能。在这种情况下,我会重命名valuehasData或者isLoadingData. 良好的编码和命名实践将为您节省时间、金钱、头发,甚至工作。


推荐阅读