javascript - 如何仅在数据之前加载微调器
问题描述
我试图让我的Spinner
组件仅在加载 API 数据之前显示,否则,它应该被隐藏。我创建了一个名为的变量value
并将其设置为每当获取 API 信息时,但在使用and指令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
}
另一种方法是根据' 的长度的当前值value
转换为computed
返回:true/false
cryptoData
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
, 被认为是不好的做法)。良好的做法是使用描述性名称,宣布所执行的角色或功能。在这种情况下,我会重命名value
为hasData
或者isLoadingData
. 良好的编码和命名实践将为您节省时间、金钱、头发,甚至工作。
推荐阅读
- flutter - 在未标记为 @immutable 的类上重载运算符 == 和 hashCode
- react-native - 如何在本机反应中访问静态/本地文件
- .net - 方法第二次不起作用。(使用流读取 POST 内容时出现问题) Aspx .NET
- javascript - 表单提交事件未向函数提交值
- python - Python:SSH 到远程终端和 telnet 到 localhost
- amazon-web-services - 在 Amazon EC2 实例上设置 AWS Application Load Balancer VS Nginx 负载均衡器的定价
- oracle - 限制周日在 oracle 中创建表
- javascript - Outlook 加载项桌面 - 显示 google oauth 2 对话框
- java - QuerySyntaxException:意外令牌:FROM
- cloud - JIRA 云与 Tenable.io 的集成