您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)Vue請求JSON Server服務(wù)器數(shù)據(jù)的實現(xiàn),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
json的數(shù)據(jù)結(jié)構(gòu)
這是之前所請求的json數(shù)據(jù):
{ "status":0 ,"message":[ { "id":1 ,"name":"張三" } ,{ "id":2 ,"name":"李四" } ] }
如果我們直接使用之前所使用的json數(shù)據(jù),其在JSON Server中執(zhí)行下面命令啟動服務(wù)器:
json-server db.json
在控制臺中我們會看到,其是會報錯的,其報的錯誤代碼如下:
\{^_^}/ hi! Loading db.json Done Type of "status" (number) in db.json is not supported. Use objects or arrays of objects.
上面的意思是說,在status后面不應(yīng)該直接跟數(shù)字0而是應(yīng)該跟一個Object對象或者是數(shù)組對象。之所以出現(xiàn)這種情況,其主要是因為在JSON Server的json頂級對象中,其是不允許直接跟字符串或數(shù)字的,而是應(yīng)該跟Object對象或者是數(shù)組對象。
所以說上面的json數(shù)據(jù)應(yīng)該修改如下:
{ "people": { "status": { "status": 0 }, "message": [ { "id": 1, "name": "張三" }, { "id": 2, "name": "李四" } ] } }
現(xiàn)在再次執(zhí)行下面的代碼啟動服務(wù)器:
json-server db.json
其啟動后的結(jié)果如下:
\{^_^}/ hi! Loading db.json Done Resources http://localhost:3000/status http://localhost:3000/message Home http://localhost:3000 Type s + enter at any time to create a snapshot of the database
我們可以看到,現(xiàn)在JSON Server已經(jīng)啟動成功!
請求的url地址
我們在這里不能直接使用http://localhost:3000的請求地址,然后再獲取響應(yīng)信息后直接點出來,原因如下:
從這里,我們可以看到,我們所獲取的實際上返回的是一個頁面,我們是不能對頁面直接點出來數(shù)據(jù)然后再操作的。即我們?nèi)绻陧憫?yīng)結(jié)果中使用res.body,其返回的結(jié)果為:
此時我們訪問的url地址應(yīng)該為:
http://localhost:3000/people
其響應(yīng)后的結(jié)果為:
從這里我們可以看出,這才是我們所期望得到的結(jié)果。
從后臺獲取vue-resource的數(shù)據(jù)源
基本上,在上面兩點注意事項修改完成后,下面的代碼就可以運行了,因而這里就不必再多說了,直接上完整源碼:
源碼
.html源碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vue-router</title> </head> <body> <div id="app"> <ul> <li v-for="item in list">{{item.name}}</li> </ul> </div> <script src="../../../../js/vue/vue/1.0/vue.js"></script> <script src="../../../../js/vue/vue-resource/1.2.1/vue-resource.js"></script> <script type="application/javascript"> var vm = new Vue({ el:'#app' ,data:{ list:[] } ,created(){ this.getData(); } ,methods:{ getData(){ var url = 'http://localhost:3000/people'; this.$http.get(url).then(function(res){ var body = res.body; if(!body.status){ alert('請求出錯!'); } this.list = body.message; }); } } }); </script> </body> </html>
db.json源碼:
{ "people": { "status": { "status": 0 }, "message": [ { "id": 1, "name": "張三" }, { "id": 2, "name": "李四" } ] } }
運行結(jié)果
看完上述內(nèi)容,你們對Vue請求JSON Server服務(wù)器數(shù)據(jù)的實現(xiàn)有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。