vue,一路走來(3)--數據交互vue-resource

 全部的靜態頁面佈局完成後,最重要的就是數據交互了,簡單來講,vue-resource就像jquery裏的$.ajax,用來和後臺交互數據的。放在created或ready裏運行來獲取或者更新數據的。不過,vue更新到2.0以後,做者就宣告再也不對vue-resource更新,而是推薦的axios(可自行去了解)。但我在項目中用的是vue-resource,下面就來說一下過程當中遇到的問題吧!vue

vue-resource(數據交互)jquery

1.先安裝 cnpm install vue-resource --savewebpack

而後在main.js中引入:ios

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請求數據web

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提交數據ajax

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表單同樣。npm

Vue.http.options.emulateJSON = true;

在使用的時候遇到一個小坑,這個$http請求和jquery的ajax仍是有點區別,這裏的post的data默認不是以form data的形式,而是request payload。解決起來也很簡單,將emulateJSON 屬性設置爲true便可。

 在本地發送API接口請求,遇到跨域問題json

後臺用了Nginx代理,後面看到有人分享說Vue.js的webpack模板中自帶了一個代理axios

還遇到了由於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
})
相關文章
相關標籤/搜索