最近使用vue-cli做了一個(gè)小小的項(xiàng)目初狰,在項(xiàng)目中需要使用vue-resource來與后臺(tái)進(jìn)行數(shù)據(jù)交互,所以我使用了本地json數(shù)據(jù)來模仿后臺(tái)獲取數(shù)據(jù)的流程互例。
至于vue-resource的安裝和json的準(zhǔn)備我就不贅述了奢入、、媳叨、
下面是操作方法:
1腥光、首先介紹一下項(xiàng)目的結(jié)構(gòu):將本地的json文件放在最外層和index.html在一起,姑且叫做data.json糊秆。
我的json數(shù)據(jù)文件大概如此:
{
"seller": {
"name": "粥品香坊(回龍觀)",
"description": "蜂鳥專送",
"bulletin": "會(huì)指定餐飲服務(wù)商柴我。",
"avatar": "http://static.galileo.xiaojukeji.com/static/tms/seller_avatar_256px.jpg",
},
"goods": [
{
"name": "熱銷榜",
"type": -1
},
{
"name": "熱銷榜",
"type": -1
}
],
"ratings": [
{
"username": "3******c",
"avatar": "http://static.galileo.xiaojukeji.com/static/tms/default_header.png",
"recommend": [
"南瓜粥",
"皮蛋瘦肉粥"
]
},
{
"username": "2******3",
"avatar": "http://static.galileo.xiaojukeji.com/static/tms/default_header.png",
"recommend": [
"扁豆?fàn)F面"
]
}
]
}
2、接著在build的dev-server.js中進(jìn)行加入代碼:
//模擬服務(wù)器返回?cái)?shù)據(jù)--開始
var appData = require('../data.json');
var seller = appData.seller;
var goods = appData.goods;
var ratings = appData.ratings;
var apiRoutes = express.Router();
apiRoutes.get('/seller', function (req, res) {
res.json({
errno: 0,
data: seller
});
});
apiRoutes.get('/goods', function (req, res) {
res.json({
errno: 0,
data: goods
});
});
apiRoutes.get('/ratings', function (req, res) {
res.json({
errno: 0,
data: ratings
});
});
app.use('/api', apiRoutes);
//模擬服務(wù)器返回?cái)?shù)據(jù)--結(jié)束
特別注意:修改好后重新進(jìn)行cnpm run dev(注意當(dāng)dev-server.js和db.json改變后都需要進(jìn)行該步驟)扩然。
解釋下以上代碼:
1》首先請(qǐng)求根目錄下的data.json文件艘儒,獲取到文件內(nèi)容并將其賦值給appData變量,然后獲取其中的各個(gè)字段數(shù)據(jù)夫偶,分別定義變量seller界睁、goods,ratings來賦值。
2》之后兵拢,通過express提供的Router對(duì)象及其一些方法(這里用的get方法)來設(shè)置接口(請(qǐng)求路徑)以及請(qǐng)求成功后的回調(diào)函數(shù)來處理要返回給請(qǐng)求端的數(shù)據(jù)翻斟。(errno這個(gè)類似以js請(qǐng)求中的code值)
3》最后,我們要“使用”這個(gè)Router對(duì)象说铃,為了統(tǒng)一管理api接口访惜,我們?cè)谝?qǐng)求的路由前邊都加上‘a(chǎn)pi/’來表明這個(gè)路徑是專門用來提供api數(shù)據(jù)的嘹履。在這個(gè)“接口”中,當(dāng)我們?cè)L問“http://localhost:8080/api/sites”路徑的時(shí)候债热,就會(huì)返回db.json里的sites對(duì)象給我們砾嫉。
3、使用resouce獲取這些數(shù)據(jù)窒篱,并使用
export default{
data () {
return {
seller: {}
};
},
created () {
this.$http.get('/api/seller').then((response) => {
// console.log(response);
response = response.body;
const ERR_OK = 0;
if (response.errno === ERR_OK) {
let data = response.data;
console.log(data);
}
});
},
components: {
'v-header': header
}
};