使用ES6箭头函数作为AJAX回调处理程序

时间:2019-11-05 12:36:39

标签: javascript vue.js ecmascript-6 arrow-functions

Vue lifecycle hook中,我有以下AJAX呼叫

mSCA.setViewBinder(new SimpleCursorAdapter.ViewBinder(){
   /** Binds the Cursor column defined by the specified index to the specified view */
   public boolean setViewValue(View view, Cursor cursor, int columnIndex){
       if(view.getId() == R.id.your_image_view_id){
           String yourImageNameFromDb = cursor.getString(2);
           int resID = getResources().getIdentifier(yourImageNameFromDb , "drawable", getPackageName());

          ((ImageView)view).setImageDrawable(getResources().getDrawable(resID));
           return true; //true because the data was bound to the view
       }
       return false;
   }
});

是否可以使用箭头函数来处理AJAX调用的结果?我尝试了以下

created: function () {

  axios.get(`/list-suppliers/${this.newAwardNdc}`).then(function (response) {
    this.supplierCount = _.uniqBy(response.data, 'groupNumber').length;
  }.bind(this));
}

但是它失败了,因为created: function () { axios.get(`/list-suppliers/${this.newAwardNdc}`).then(response => { this.supplierCount = _.uniqBy(response.data, 'groupNumber').length; }); } 没有正确绑定。

1 个答案:

答案 0 :(得分:0)

由于documentation you've linked与promise handler箭头功能一起使用时,您可能希望提供其他上下文。

new Vue({
  data: {
    a: 1
  },
  created: function () {
    console.log(this.a, this.supplierCount);
    axios.get("https://api.myjson.com/bins/xva5k").then(response => {
      this.supplierCount = _.uniqBy(response.data, 'groupNumber').length;
      console.log(this.a, this.supplierCount);
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>