反应性在Vue组件内无效

时间:2018-02-17 14:03:02

标签: vue.js

我已经定义了一个Vue组件,其中数据"设施"被定义为。来自JQuery的工具中的更新不会引发反应。我可以看到我成功收到了api电话的响应。

我的部分代码如下。

    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 = [];
            }
          })

  }
}

但是,jQuery更新中的facilities更新(在created()内部)不会触发任何Reactivity。

1 个答案:

答案 0 :(得分:1)

成功回调中的

this不引用组件实例。组件的数据不会因为您永远不会更改而改变。试试这个:

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

或者:

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