vue,一路走来(3)--数据交互vue-resource

 所有的静态页面布局完成后,最重要的就是数据交互了,简单来说,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
})

 

posted @ 2017-05-24 22:09  童话里都是骗人的  阅读(1492)  评论(0编辑  收藏  举报