[英]How can I have the spinner load only before the data
我試圖讓我的Spinner
組件僅在加載 API 數據之前顯示,否則它應該被隱藏。 我創建了一個名為value
的變量,並在獲取 API 信息時將其設置為true
,但是在使用v-if
和v-else
指令時我似乎弄錯了。 目前使用v-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>
您在 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
}
另一種方法是根據cryptoData
長度的當前值將value
轉換為computed
的返回true/false
:
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
被認為是不好的做法)。 好的做法是使用描述性名稱,宣布角色或執行的 function。 在這種情況下,我會將value
重命名為hasData
或者isLoadingData
。 良好的編碼和命名實踐將為您節省時間、金錢、頭發,甚至工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.