使用 Vue 开发 API
这个例子
欢迎来到API,请问您要点什么?
在 Vue 中访问 API
大多数应用在某种程度上都会使用数据,而这些数据很可能来自 API。在本教程中,我们将使用 Vue 来获取数据并将其显示出来。
这个例子
假设你需要显示北美国家/地区的列表。该列表将显示国家/地区、首都和人口。
你找到了名为REST Countries 的API ,它包含国家面积和人口数据——正是你需要的。
欢迎来到API,请问您要点什么?
仔细想想,API有点像汽车餐厅的点餐服务,你发出请求,然后得到响应。但是,你需要了解一些基本知识,例如:
1. 食物/数据位于哪里?
你需要知道餐厅的地址,就像你需要知道API的URL一样。
2. 菜单上有什么?
你是要“薯条”还是“薯片”?
是的,它们是一样的,但你需要使用正确的词语/参数才能得到你想要的东西。
3. 你能得到什么?
当你收到一个装在包裹里的食物/数据时,你需要知道里面装的是什么。是番茄酱还是醋?同样,返回的数据字段和格式是什么?
4. 您可以提出特殊要求吗?
如何获取额外的餐巾纸/申请特定字段?
请阅读菜单
在开始项目之前,最好先了解一下 API 的相关内容。查看一下菜单/文档,这将使工作更加轻松。
在 Vue 中访问 API
Vue 是一个 JavaScript 框架,因此它没有专门的 API 使用方法。Ajax 或 Fetch 都可以。Axios经常被推荐,因为它简单易用且效果不错,所以我们会使用它。
理论就讲到这里,让我们拿起键盘开始编写代码吧!
基本设置
为了简单起见,我们将用网页来构建这个应用程序。
为此,我们将使用两个文件,
- 用于显示数据并加载 Vue 文件的 HTML 文件。
- Vue 文件包含代码。
HTML 文件:
<html lang="en">
<head>
<!-- Load Vue -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- Load script file. 'defer' loads after body is generated -->
<script src="vue_lists.js" defer></script>
<style>
table,
th,
td {
border: 1px solid #cccccc;
border-collapse: collapse;
}
</style>
</head>
<body>
<h1>North America</h1>
<!-- Div where Vue runs -->
<div id="app">
<h2>Table</h2>
<table>
<tr>
<th>Country</th>
<th>Capital</th>
<th>Population</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
</body>
</html>
Vue.js 文件:
在这个文件中,我们使用名为“countries_list”的数组来存储数据。目前它是空的。
var app = new Vue({
el: '#app',
data: {
countries_list: [],
},
})
正在加载 Axios
要在应用程序中使用 Axios,需要先加载它。为了简单起见,我们将使用 CDN,并将其添加到 HTML 头部。
<!-- Load Axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
现在它已经加载完毕,你可以在 Vue 中访问它了。
获取数据
回到免下车餐厅的比喻。我们坐在车里(Axios),准备出发。我们知道地址(网址),也阅读了菜单(文档),所以知道该点什么(网址字符串)。
下单吧!
根据文档,请求字符串应如下所示:https://restcountries.eu/rest/v2/region/americas
太好了!我们知道如何获取数据了,现在让我们把它显示在屏幕上。数据应该在页面加载完成后立即显示,那么该怎么做呢?
把它挂在钩子上
Vue 有一系列生命周期钩子,会在加载过程中的特定阶段触发。“ mounted ”钩子会在 DOM 加载完成后触发。这行得通!我们把 Axios 调用放进去,并进行设置,以便查看控制台日志中的原始数据。
mounted() {
axios
.get('https://restcountries.eu/rest/v2/region/americas')
.then(response => (
console.log(response)
))
}
分解:
| mounted() { ...} | 当 DOM 加载完毕 |
| 公理 | 请告诉 Axios…… |
| 。得到 (....) | 使用“get”方法访问此URL并返回数据 |
| 。然后 (...) |
数据返回后…… |
| response => ( console.log(response) ) |
将数据称为“响应”,并在控制台日志中显示。 |
整合
代码应该类似于这样:
HTML
<html lang="en">
<head>
<!-- Load Vue -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- Load Axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- Load script file. 'defer' loads after body is generated -->
<script src="vue_lists.js" defer></script>
<style>
table,
th,
td {
border: 1px solid #cccccc;
border-collapse: collapse;
}
</style>
</head>
<body>
<h1>North America</h1>
<!-- Div where Vue runs -->
<div id="app">
<h2>Table</h2>
<table>
<tr>
<th>Country</th>
<th>Capital</th>
<th>Population</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
</body>
</html>
Vue.js 文件:
var app = new Vue({
el: '#app',
data: {
countries_list: [],
},
mounted() {
axios
.get('https://restcountries.eu/rest/v2/region/americas')
.then(response => (
console.log(response)
))
}
})
控制台日志中的数据如下所示:
{data: Array(57), status: 200, statusText: "", headers: {…}, config: {…}, …}
config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data: (57) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
headers: {content-type: "application/json;charset=utf-8", cache-control: "public, max-age=86400"}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: ""
__proto__: Object
它拥有我们需要的一切,甚至更多!
取出你需要的东西
就像在汽车餐厅一样,你需要打开包裹才能获得食物/数据。
我们在这里看到的是完整的响应,包括状态、标头,也就是整个数据包。这就像在汽车餐厅窗口拿到一个袋子,我们不需要包装纸,只需要食物(数据),所以我们需要稍微“解包”一下。你可以通过修改代码来返回响应数据。
.then(response => (
console.log(response.data)
))
提示:由于响应会返回所有信息,因此它是一个很好的调试工具。
控制台日志应该类似于:
(57) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {name: "Anguilla", topLevelDomain: Array(1), alpha2Code: "AI", alpha3Code: "AIA", callingCodes: Array(1), …}
1: {name: "Antigua and Barbuda", topLevelDomain: Array(1), alpha2Code: "AG", alpha3Code: "ATG", callingCodes: Array(1), …}
2: {name: "Argentina", topLevelDomain: Array(1), alpha2Code: "AR", alpha3Code: "ARG", callingCodes: Array(1), …}
这样好多了!
使数据可用
下一步是将数据赋值给一个变量,以便我们可以在 HTML 文件中使用它。
.then(response => (
this.countries_list = response.data
))
现在 countries_list 有了数据,我们将设置 HTML 页面来显示它。
显示数据
我们已经在 HTML 文件中设置好了表格,现在只需要把数据放进去就行了。
目前,数据存储在一个名为“countries_list”的数组中。关键在于遍历该数组并将其显示在表格中。这可以通过使用“ v-for ”来实现,它类似于 Vue 中的“for 循环”。你需要将一个元素放入其中,该元素会针对数据库中的每条记录重复执行。
我们的例子如下所示:
<tr v-for="country in countries_list">
<td>{{country.name}}</td>
<td>{{country.capital}}</td>
<td>{{country.population}}</td>
</tr>
分解:
| <tr v-for="country in countries_list"> | 为“ country_list ”中的每个记录创建一个<tr>, 每个记录将被命名为“ country ”。 |
<td>{{country.name}}</td> <td>{{country.capital}}</td> <td>{{country.population}}</td> |
在 Vue 中显示数据时,需要使用双花括号。 因此,对于每条记录,创建一个 <td> 元素 ,并将数据(名为“ country ”) 和字段(名称、首都、人口等)用花括号括起来。 |
| </tr> | 行尾。 |
HTML页面应如下所示:
<html lang="en">
<head>
<!-- Load Vue -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- Load Axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- Load script file. 'defer' loads after body is generated -->
<script src="vue_lists.js" defer></script>
<style>
table,
th,
td {
border: 1px solid #cccccc;
border-collapse: collapse;
}
</style>
</head>
<body>
<h1>North America</h1>
<!-- Div where Vue runs -->
<div id="app">
<h2>Table</h2>
<table>
<tr>
<th>Country</th>
<th>Capital</th>
<th>Population</th>
</tr>
<tr v-for="country in countries_list">
<td>{{country.name}}</td>
<td>{{country.capital}}</td>
<td>{{country.population}}</td>
</tr>
</table>
</div>
</body>
</html>
表格应如下所示:
| 国家 | 首都 | 人口 |
|---|---|---|
| 安圭拉 | 山谷 | 13452 |
| 安提瓜和巴布达 | 圣约翰 | 86295 |
| 阿根廷 | 布宜诺斯艾利斯 | 43590400 |
| 阿鲁巴 | 奥兰杰斯塔德 | 107394 |
| 巴哈马 | 拿骚 | 378040 |
| 巴巴多斯 | 布里奇敦 | 285000 |
我们取得进展了!
在元素中使用 API
(或如何在 <img 和其他标签中使用 Vue)
这个API为每个国家都提供了一个国旗图片。这是一个很好的视觉提示,所以我们把它添加到国家旁边。
虽然在 Vue 中显示 API 数据时使用双花括号,但当将其应用于 HTML 元素(例如图像标签)时,其工作方式有所不同。
这里使用v-bind将数据绑定到属性。因此,图像标签看起来会像这样:
<img v-bind:src="country.flag" alt="Flag" height="26" width="42">
我们把它添加到表格里。
<tr v-for="country in countries_list">
<td>
<img v-bind:src="country.flag" alt="Flag" height="26" width="42">
{{country.name}}
</td>
<td>{{country.capital}}</td>
<td>{{country.population}}</td>
</tr>
传递参数
通过此 API,您可以向其传递一个参数,告诉它要返回哪些字段。我们只需要
- 国家
- 简短形式
- 尺寸
- 人口
- 旗帜
根据文档,URL 应如下所示:
https://restcountries.eu/rest/v2/region/americas? fields=name;capital;flag;population
我们可以将 Axios 调用更改为:
mounted() {
axios
.get('https://restcountries.eu/rest/v2/region/americas?fields=name;capital;flag;population')
.then(response => (
this.countries_list = response.data,
console.log(response.data)
))
}
结果没有任何变化,但如果你查看控制台,只会看到你需要的数据。很简单,对吧?
[{"flag":"https://restcountries.eu/data/aia.svg","name":"Anguilla","capital":"The Valley","population":13452},{"flag":"https://restcountries.eu/data/atg.svg","name":"Antigua and Barbuda","capital":"Saint John's","population":86295},{"flag":"https://restcountries.eu/data/arg.svg","name":"Argentina","capital":"Buenos Aires","population":43590400},{"flag":"https://restcountries.eu/data/abw.svg","name":"Aruba","capital":"Oranjestad","population":107394},
.....
在这种情况下传递参数很简单——只需一个“get”字符串即可。当然,有些 API 和应用程序更复杂,可能需要“post”变量等等。Axios 在传递变量方面做得很好,还有很多其他功能。更多信息请参见:https://github.com/axios/axios
处理错误和缺失数据
如果出现问题怎么办?数据没有返回,餐厅关门了,那该怎么办?
你需要使用 catch 语句。catch 语句会捕获错误,以便你优雅地处理它。
.catch(error =>(
console.log(error)
));
通常情况下,你需要告知用户存在问题。虽然你可以在 catch error 语句中编写一些代码,但更简便的方法可能是在 HTML 文件中使用v-if语句。
在这种情况下,如果“countries_list”为空,则需要告知用户。这可以通过在HTML页面中添加另一行来实现,该行会在“countries_list.length”为0时显示。
<tr v-if="countries_list.length == 0">
<td colspan="3">
No records found.
</td>
</tr>
分解:
| <tr v-if="countries_list.length == 0"> | 如果数组 countries_list 的长度为零,则创建一个<tr>元素。 |
<td colspan="3"> 未找到记录。 </td> |
只需要一个 td 元素即可展开所有三列。我们仍然有 3 个标题列。 |
| </tr> | 行尾。 |
重要提示!如果生成了列表,请确保“错误行”位于已生成的行之外。它们是两回事!
您的表格应该类似于:
<table>
<!-- Header -->
<tr>
<th>Country</th>
<th>Capital</th>
<th>Population</th>
</tr>
<!-- Country List -->
<tr v-for="country in countries_list">
<td>
<img v-bind:src="country.flag" alt="Flag" height="26" width="42">
{{country.name}}
</td>
<td>{{country.capital}}</td>
<td>{{country.population}}</td>
</tr>
<!-- Error Row -->
<tr v-if="countries_list.length == 0">
<td colspan="3">
No records found.
</td>
</tr>
</table>
最终产品
我们的HTML代码应该如下所示:
<html lang="en">
<head>
<!-- Load Vue -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- Load Axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- Load script file. 'defer' loads after body is generated -->
<script src="vue_lists.js" defer></script>
<style>
table,
th,
td {
border: 1px solid #cccccc;
border-collapse: collapse;
}
</style>
</head>
<body>
<h1>North America</h1>
<!-- Div where Vue runs -->
<div id="app">
<h2>Table</h2>
<table>
<!-- Header -->
<tr>
<th>Country</th>
<th>Capital</th>
<th>Population</th>
</tr>
<!-- Country List -->
<tr v-for="country in countries_list">
<td>
<img v-bind:src="country.flag" alt="Flag" height="26" width="42">
{{country.name}}
</td>
<td>{{country.capital}}</td>
<td>{{country.population}}</td>
</tr>
<!-- Error Row -->
<tr v-if="countries_list.length == 0">
<td colspan="3">
No records found.
</td>
</tr>
</table>
</div>
</body>
</html>
我们的 Vue 脚本应该如下所示:
var app = new Vue({
el: '#app',
data: {
countries_list: [],
},
mounted() {
axios
.get('https://restcountries.eu/rest/v2/region/americas?fields=name;capital;flag;population')
.then(response => (
this.countries_list = response.data
))
.catch(error =>(
console.log(error)
));
}
})
我们的清单应该看起来像这样:
| 国家 | 首都 | 人口 |
|---|---|---|
| 山谷 | 13452 | |
| 圣约翰 | 86295 | |
| 布宜诺斯艾利斯 | 43590400 | |
| 奥兰杰斯塔德 | 107394 | |
| 拿骚 | 378040 | |
| 布里奇敦 | 285000 | |
| 贝尔莫潘 | 370300 | |
| 汉密尔顿 | 61954 |
总结
在 Vue 中使用 API 非常简单。只需确保你知道如何获取数据(例如,免下车点餐数据),将其赋值给一个数组变量,然后在 HTML 中显示即可。
资源
更多信息:
文章来源:https://dev.to/workingwebsites/using-vue-for-apis-k4j