0

I have defined a Vue component where the data "facilities" is defined. The Update in the facilities from the JQuery is not triggering reactivity. I can see that I am getting the response from my api call successfully.

Part of my code is as below.

    export default {
  name: 'facility',
  computed: {
    numberOfParkings: function(){
      return this.facilities.length;
    },
    totalParking: function(){
      var total = {cars: 0, bikes: 0};
      for(var i=0; i< this.facilities.length; i++){
        total.cars += this.facilities[i].currentlyAvailableParking.cars;
        total.bikes += this.facilities[i].currentlyAvailableParking.bikes;
      }

      return total;
    }
  },
  data () {
    return {
      facilities: [],
      nodata: false
    }
  },
  created(){
          var $ = require("jquery");
          console.log("Called");
          var data = {
              "location": {
                  "latitude": "12.8928365",
                  "longitude": "77.70749120000005"

             },
              "radius": 2
               };
          $.ajax({
            url: 'http://localhost:1337/hubs/fetchAll',
            method: "POST",
            data: data,
            success: function(response){
              this.facilities = response;
            },
            error: function(jq,err){
              this.facilities = [];
            }
          })

  }
}

However, the update in the facilities inside the jQuery update (inside created()) is not triggering any Reactivity.

Rajive Pai
  • 312
  • 1
  • 13

1 Answers1

1

this inside success callback doesn't refer to the component instance. The data of your component does not change simply because you never change it. Try this:

const self = this;
$.ajax({
    url: 'http://localhost:1337/hubs/fetchAll',
    method: "POST",
    data: data,
    success: function(response){
        self.facilities = response;
    },
})

Or :

$.ajax({
    url: 'http://localhost:1337/hubs/fetchAll',
    method: "POST",
    data: data,
    success: (response) => {
        this.facilities = response;
    },
})
oniondomes
  • 2,034
  • 13
  • 22