具體的代碼請(qǐng)移步github
GitHub:https://github.com/Ewall1106/mall(請(qǐng)選擇分支15)
一、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í)踐一波。愛掏網(wǎng) - it200.com
二、新建mock.json
1、我們先在static文件夾下新建一個(gè)mock文件,里面放上我們首頁所需要的數(shù)據(jù)
(1)先是輪播圖的數(shù)據(jù),我們把首頁中的輪播圖鏈接復(fù)制過來:

(2)然后是分類的icon圖片和推薦模塊相關(guān)數(shù)據(jù)

三、axios的安裝和數(shù)據(jù)mock的一些配置
1、然后我們動(dòng)手先安裝一波axios
和express
,為什么要用到express,因?yàn)槲覀償?shù)據(jù)的mock中需要用到express框架實(shí)現(xiàn),后面我們?cè)谠敿?xì)講解expres。愛掏網(wǎng) - it200.com
(1)安裝express、axios
$ npm install express --save
$ npm install axios --save

(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()
// 通過路由請(qǐng)求本地?cái)?shù)據(jù)
app.use('/api', router)

(3)devServer中添加before
方法
// 添加before方法
before(app) {
app.get('/api/appData', (req, res) => {
res.json({
errno: 0,
data: appData
})
})
}

四、使用axios獲取mock數(shù)據(jù)
1、我們進(jìn)入hom.vue頁面先引入axios;
2、然后我們?cè)?code>methods中寫個(gè)函數(shù):用axios
獲取首頁數(shù)據(jù)并打印,然后當(dāng)vue生命周期為mounted
階段時(shí)調(diào)用它:

3、最后我們進(jìn)入瀏覽器中看看數(shù)據(jù)是不是打印出來了

ok,我們mock的數(shù)據(jù)都拿到了。愛掏網(wǎng) - it200.com到了這一步,接下來就簡單了,無非是把值傳給組件,然后將數(shù)據(jù)渲染到頁面上,這個(gè)我們下篇講。愛掏網(wǎng) - it200.com
參考學(xué)習(xí)
https://github.com/axios/axios
https://github.com/Ewall1106/mall
https://www.jianshu.com/p/986821d35988
https://www.jianshu.com/p/4f92c4461e3d
https://www.jianshu.com/p/004b73f3f589