具體的代碼請(qǐng)移步github
GitHub:https://github.com/Ewall1106/mall
1侵歇、axios官方文檔基本閱讀
- 我們先從官方實(shí)例上上看看
axios
的用法:https://github.com/axios/axios
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// Want to use async/await? Add the `async` keyword to your outer function/method.async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
- 上面的記個(gè)大概就好言秸,我們動(dòng)手實(shí)踐一波洒闸。
2舆瘪、新建mock.json
- 我們先在static文件夾下新建一個(gè)mock文件诀姚,里面放上我們首頁(yè)所需要的數(shù)據(jù)
(1)先是輪播圖的數(shù)據(jù)疮茄,我們把首頁(yè)中的輪播圖鏈接復(fù)制過(guò)來(lái):
mock數(shù)據(jù)
(2)然后是分類(lèi)的icon圖片和推薦模塊相關(guān)數(shù)據(jù)
mock數(shù)據(jù)
3吝梅、axios的安裝和數(shù)據(jù)mock的一些配置
- 然后我們動(dòng)手先安裝一波
axios
和express
伦吠,為什么要用到express妆兑,因?yàn)槲覀償?shù)據(jù)的mock中需要用到express框架實(shí)現(xiàn),后面我們?cè)谠敿?xì)講解expres毛仪。
(1)安裝express搁嗓、axios
$ npm install express --save
$ npm install axios --save
install express and axios
(2)在webpack.dev.conf.js的頭部中引入
// mock數(shù)據(jù)
const express = require('express')
const app = express()
var appData = require('../static/mock/mock.json')
var router = express.Router()
// 通過(guò)路由請(qǐng)求本地?cái)?shù)據(jù)
app.use('/api', router)
config配置
(3)devServer中添加before
方法
// 添加before方法
before(app) {
app.get('/api/appData', (req, res) => {
res.json({
errno: 0,
data: appData
})
})
}
before()
4、使用axios獲取mock數(shù)據(jù)
我們進(jìn)入hom.vue頁(yè)面先引入axios箱靴;
然后我們?cè)?code>methods中寫(xiě)個(gè)函數(shù):用
axios
獲取首頁(yè)數(shù)據(jù)并打印腺逛,然后當(dāng)vue生命周期為mounted
階段時(shí)調(diào)用它:
使用axios獲取數(shù)據(jù)
- 最后我們進(jìn)入瀏覽器中看看數(shù)據(jù)是不是打印出來(lái)了
瀏覽器console
- ok,我們mock的數(shù)據(jù)都拿到了衡怀。到了這一步棍矛,接下來(lái)就簡(jiǎn)單了,無(wú)非是把值傳給組件抛杨,然后將數(shù)據(jù)渲染到頁(yè)面上够委,這個(gè)我們下篇講。
參考學(xué)習(xí)
https://github.com/axios/axios
https://github.com/Ewall1106/mall
http://www.reibang.com/p/986821d35988
http://www.reibang.com/p/4f92c4461e3d
http://www.reibang.com/p/004b73f3f589