發現在學習vue的時候,不論你用的是哪種編程工具,是否使用打包和腳手架,都需要手工的多練習,只能說步步是坑.
在使用的過程中一定要多按F12,多寫console.log來看輸出的值是什么,非常有助於排錯和知道返回的是啥東西
1、在vue的data中定義一個數組pingxuanren,用於存放從服務器端請求來的數據
data:{ pingxuanren:[], //需要評分的人員信息 userinfo:[], //用戶自己的身份信息 userxx:'' },
2、然后簡單的封裝一下axios的post請求,我也是從網上看了很多,抄了一下,自己並不會寫。
//封裝一下axios的POST請求 axiosPost:function(url,params){ return new Promise((resolve, reject) => { axios({ url: url, method: 'post', data: params, transformRequest: [function(data) { let ret = '' for(let it in data) { ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&' } return ret }], headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .then(res=>{ resolve(res.data); }) }); },
上面的直接復制就能用,返回的數據存儲在Promise對像中,只要知道數據返回了就行了.
3、具體的使用中需要注意params的參數,一定要寫.then,返回的數據就是res,直接用就可以了.
1 //返回被評分人的信息列表 2 getyunangong:function(){ 3 var yhm=localStorage.getItem('yhm'); 4 5 var url='test.ashx?method=yuangong'; 6 var params={yhm_:yhm}; 7 this.axiosPost(url,params) 8 .then(res=>{ 9 this.pingxuanren=res; 10 }) 11 },
4、pingxueren數組中就已經有數組了,可以讀取綁定到頁面上了。
再看看原來的寫法,亂的一批,每有不同的請求都得重寫一次。
axios({ url: 'test.ashx?method=savedata', method: 'post', data: { title_: _title, fen_: mes, yhm:localStorage.getItem('yhm'), tofen:localStorage.getItem('tofen'), }, transformRequest: [function(data) { let ret = '' for(let it in data) { ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&' } return ret }], headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .then(function (response) { var info=response.data; //console.log(info); if (info===401){ alert("保存數據時出錯了!"); }else{ alert("保存成功,點擊'確定'將跳轉至主評分頁面!"); localStorage.removeItem('tofen'); window.location.href="home.htm"; }