从axios返回一个数组?

时间:2017-03-16 13:31:21

标签: javascript vue.js vuejs2 axios vue-resource

我正在研究Vue.js的计算属性

有一个计算方法请求axios api获取一个数组(在promise中执行了一些逻辑之后)。

computed: {
    filteredTrips: function () {
        var filtered = this.trips;
        if(this.filters_by.indexOf('monitor')>=0) filtered = this.filter(filtered, this.BusMonitorID,'BusMonitorID');
        if(this.filters_by.indexOf('route')>=0) filtered =  this.filter(filtered,  this.TourID,'TourID');
        if(this.filtered_count==0) return this.getFilteredTrips(); //This is the axios method to get an array
        return filtered;
    }
},
methods: {
    getFilteredTrips:function(){
      var resource = base_url+'report/transport/filter';
      var self = this;
      axios.post(resource, $.param({filters:this.filters})).then(function(response) {
        // here i'm performing some logics to make self.trips

        self.trips.push(data[trip]); //push data to self.trips

        return self.trips; // i need to return this array
      }).catch(function(response) {
            // error callback
        })
     }
}

问题是getFilteredTrips()没有返回self.trips数组,  如何通过axios / js实现它?

1 个答案:

答案 0 :(得分:0)

计算属性不能像进行后端调用那样具有异步任务,您应该使用方法而不是计算属性来调用此方法:getFilteredTrips

您可以拥有一个数据:filteredTrips,您可以在getFilteredTrips功能中进行更新。您的代码看起来应该是:

data:{
  return {
    filteredTrips: []
  }
},
computed: {
    filteredTripsComputed: function () {
        var filtered = this.trips;
        if(this.filters_by.indexOf('monitor')>=0) filtered = this.filter(filtered, this.BusMonitorID,'BusMonitorID');
        if(this.filters_by.indexOf('route')>=0) filtered =  this.filter(filtered,  this.TourID,'TourID');
        return filtered;
    }
},
methods: {
    filteredTrips:function(){
        if(this.filtered_count==0) return this.getFilteredTrips(); 
         return this.filteredTripsComputed;
    }
    getFilteredTrips:function(){
      var resource = base_url+'report/transport/filter';
      var self = this;
      axios.post(resource, $.param({filters:this.filters})).then(function(response) {
        // here i'm performing some logics to make self.trips

        self.trips.push(data[trip]); //push data to self.trips

        self.filteredTrips = self.trips; // i need to return this array
      }).catch(function(response) {
            // error callback
        })
     }
}