有很多时候你在构建应用时需要访问一个 API 并展示其数据。做这件事的方法有好几种,而使用基于 promise 的 HTTP 客户端 axios 则是其中非常流行的一种。
具体使用方法通过一个实例展示:获取第一页前十条网易新闻,其中使用到了bootstrap中的多媒体对象。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vue—网易新闻</title>
<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"> </script>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-2" id="app">
<h2 class="text-center">网易新闻</h2>
<br>
<div class="media border p-3" v-for="result in results">
<a :href="result.path" target="_blank">
<img :src="result.image" alt="解析错误" class="mr-3 mt-3 " style="width:100px;"></a>
<div class="media-body">
<div>
{{result.title }}
</div>
<p>{{ result.passtime }}.</p>
</div>
</div>
</div>
<script type="text/javascript">
const vm = new Vue({
el: '#app',
data: {
results: []
},
//mounted():页面一加载就执行的操作
mounted() {
axios.get("https://api.apiopen.top/getWangYiNews?page=1&count=10")
.then(response => { this.results = response.data.result })
.catch(error => console.log(error));// 请求失败处理
}
});
</script>
</body>
</html>