11.25 Vue實戰——集成axios獲取數據構建新聞列表頁

承接上文 ,本文集成axios來獲取新聞列表數據。本項目git地址:

https://gitee.com/vuejslearn/news-list.git

首先,安裝axios

npm install axios --save

然後我們在package.json裡就會看到了axios的依賴了。

Vue實戰——集成axios獲取數據構建新聞列表頁

然後在main.js中引入、注入axios:

import axios from 'axios'

Vue.prototype.$axios = axios

然後我們就可以在全局通過this.$axios來進行http請求了。接下來,在views目錄下,新建頁面newsList.vue。然後添加created,method:

<template>

這是新聞列表頁

{{newsArray}}


/<template>




在getData函數中,添加axios的get請求:

let _this = this
this.$axios.get('https://unidemo.dcloud.net.cn/api/news')
.then(function (response) {
console.log(response.data)
_this.newsArray = response.data
})
.catch(function (error) {
console.log(error)
})

url使事先準備好的,借用Dcloud給的公共url,來獲取新聞列表,並顯示到頁面上。至於,為什麼要在axios外面寫上let_this=this呢?那是因為this的作用域問題。如果直接在then方法裡寫this,是不能代表外層的對象的。

關於axios的一些寫法:

上面所用的就是get請求:

// 為給定 ID 的 user 創建請求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

// 可選地,上面的請求可以這樣做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

post寫法:

axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

當然我們還可以用axiosAPI執行請求:

post請求:

// 發送 POST 請求 

axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});

get請求:

// 發送 GET 請求(默認的方法)
axios('/user/12345');

當我們的請求發送過去後,如果正常的話在then中我們會接收到服務端返回的信息response。其中包含:

{
// `data` 由服務器提供的響應
data: {},

// `status` 來自服務器響應的 HTTP 狀態碼
status: 200,

// `statusText` 來自服務器響應的 HTTP 狀態信息
statusText: 'OK',

// `headers` 服務器響應的頭
headers: {},

// `config` 是為請求提供的配置信息
config: {}
}

我們使用response.data獲取我們想要的數據。並顯示到頁面上。

接著,我們優化我們的newsList頁面,增加點css樣式,讓它漂亮點:

template模板:

<template>




{{news.title}}


{{news.summary}}







/<template>

css:

<style><br><br> .news-wrapper{<br> display: flex;<br> flex-direction: column;<br> justify-content: center;<br> align-items: center;<br> }<br> .news-item{<br> width: 630px;<br> margin: 10px 0;<br> border: 1px solid #f0f0f0;<br> padding: 10px 10px;<br><br> display: flex;<br> flex-direction: row;<br> justify-content: space-between;<br> align-items: center;<br><br> .content-wapper{<br> height: 100px;<br> display: flex;<br> flex-direction: column;<br> padding: 0 10px;<br><br> .title{<br> width: 440px;<br> font-size: 18px;<br> font-weight: 700;<br> line-height: 1.5;<br> margin-bottom: 5px;<br> }<br><br> .summary{<br> width: 440px;<br> font-size: 14px;<br> font-weight: 300;<br> color: #878787;<br> margin-bottom: 5px;<br> }<br> }<br><br> .img-avatar{<br> width: 150px;<br> }<br><br> }<br><br>/<style>

運行我們的項目:

Vue實戰——集成axios獲取數據構建新聞列表頁

運行結果圖

至此,axios就算集成進來了。下篇文章介紹如何抽離axios,以及優化列表頁面然他更漂亮一點。


原創不容易,鑑於本人水平有限,文中如有錯誤之處歡迎大家指正。以後我會持續發佈vue實戰系列的文章,喜歡的朋友歡迎關注。


分享到:


相關文章: