所有的靜態頁面布局完成后,最重要的就是數據交互了,簡單來說,vue-resource就像jquery里的$.ajax,用來和后台交互數據的。放在created或ready里運行來獲取或者更新數據的。不過,vue更新到2.0之后,作者就宣告不再對vue-resource更新,而是推薦的axios(可自行去了解)。但我在項目中用的是vue-resource,下面就來講一下過程中遇到的問題吧!
vue-resource(數據交互)
1.先安裝 cnpm install vue-resource --save
然后在main.js中引入:
import VueResource from 'vue-resource' Vue.use(VueResource) // 基於全局Vue對象使用http Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback); Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback); // 在一個Vue實例內使用$http this.$http.get('/someUrl', [options]).then(successCallback, errorCallback); this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback); then方法的回調函數也有兩種寫法,第一種是傳統的函數寫法,第二種是更為簡潔的ES 6的Lambda寫法: // 傳統寫法 this.$http.get('/someUrl', [options]).then(function(response){ // 響應成功回調 }, function(response){ // 響應錯誤回調 }); // Lambda寫法 this.$http.get('/someUrl', [options]).then((response) => { // 響應成功回調 }, (response) => { // 響應錯誤回調 });
如:get請求數據
this.$http.get(this._getUrl()+"Index/getApprovedCount/id/" + id).then((res)=>{ let provedCount = res.body; if(provedCount.error_code == 200){ this.getCount = provedCount.count; } });
如:post提交數據
collectaction(){ let newsid = this.$route.params.id; this.$http.post(this._getUrl()+"MyActivities/addFavorite", {"newsid":newsid},{emulateJSON:true} ).then((res)=>{ let collect = res.body; if(collect.error_code == 200){ Toast({ message:'操作成功' }) this.getCount = parseInt(this.getCount) + 1; }else{ Toast({ message:'操作失敗' }) } }) },
emulateJSON的作用
如果Web服務器無法處理編碼為application/json的請求,你可以啟用emulateJSON選項。啟用該選項后,請求會以application/x-www-form-urlencoded作為MIME type,就像普通的HTML表單一樣。
Vue.http.options.emulateJSON = true;
在使用的時候遇到一個小坑,這個$http請求和jquery的ajax還是有點區別,這里的post的data默認不是以form data的形式,而是request payload。解決起來也很簡單,將emulateJSON 屬性設置為true即可。
在本地發送API接口請求,遇到跨域問題
后台用了Nginx代理,后面看到有人分享說Vue.js的webpack模板中自帶了一個代理
還遇到了因為vue-resource是異步操作,無法實現函數調用直接return出來。
showCard(){ if(this.card_num == null || this.card_num == ""){return "";} this.$http.get("./static/json/bankData.json",{},).then((res)=>{ var bankBin = 0; var isFind = false; for(var key = 10;key >= 2;key--){ bankBin = this.card_num.substring(0,key); for(var i in res.body){ if(res.body[i].bin == bankBin){ isFind = true; return res.body[i].bankName.split("-")[0]; } } if(isFind){break;} } if(!isFind){return "未知發卡銀行";} }) }, getCard(){ console.log(this.showCard()); //undefined },
后面只能通過賦值直接輸出了,
showCard(){ if(this.card_num == null || this.card_num == ""){return this.bank="";} this.$http.get("./static/json/bankData.json",{},).then((res)=>{ var bankBin = 0; var isFind = false; for(var key = 10;key >= 2;key--){ bankBin = this.card_num.substring(0,key); for(var i in res.body){ if(res.body[i].bin == bankBin){ isFind = true; return this.bank=res.body[i].bankName.split("-")[0]; } } if(isFind){break;} } if(!isFind){return this.bank="未知發卡銀行";} }) }
<div class="card-num"> <span>銀行卡號</span> <input type="number" v-model="card_num" v-on:blur="showCard()"> <p>{{this.bank}}</p> </div>
說到這,隨便提及一下,剛好做了填寫銀行卡識別出相應的銀行,http://download.csdn.net/detail/cb511612371/9176105
后面學習了ES6的Promise的基本用法,換了一種簡單的方法。
function read( content ) { return new Promise(function( resolve,reject ) { setTimeout(function(){ if(content>4){ resolve(content) }else{ reject('小於4') } },1000) }) } read(1).then(( data )=>{ console.log(data) },( err )=>{ console.log(err) //小於4 return read(2) //將狀態改為了失敗 }) .then(( data )=>{ console.log('data',data) },( err )=>{ console.log(err) //小於4 })