在Vue中如何用新数组替换数组?

时间:2017-10-09 20:25:56

标签: vue.js

每10秒钟我会查询我的数据库以获取最新的火警呼叫。我做app.events = data.calls但我的数据没有刷新。我使用与每10秒调用的相同函数初始化数据。我看到了桌子。我如何用数组替换Vue中的数组?

<html>
<head>
  <script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
  <script src="https://unpkg.com/vue"></script>
  <script>
  $(function() {

    function getLocation() {
      if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(showPosition);
      } else {
          $('#demo').text("Geolocation is not supported by this browser.");
      }
    }
    function showPosition(position) {
      $.get('http://localhost:8000/api/nearest_events?lng='+position.coords.longitude+'&lat='+position.coords.latitude, function(data) {
        //app.$set(app.events, Object.assign({}, app.events, data.calls));
        app.events = data.calls;
      })
    }
app = new Vue({
  el: '#app',
  data: {
    events: []
  },
  created: function() {
    setInterval(getLocation(), 10000)
  }
})
  })

</script>
<style>
td, th {border:1px solid #000;padding:5px}
table { border-collapse:collapse;}
</style>
</head>
<body>
  <div id="app">
<table>
  <tr v-for="event in events">
    <td>{{ event.datetime }}</td>
    <td>{{ event.address }}</td>
    <td>{{ event.type }}</td>
    <td>
<table>
<tr><th>Unit</th><th>Dispatched at</th><th>Arrived at</th><th>In service</th></tr>
<tr v-for="unit in event.units">
<td>{{ unit.unit }}</td>
<td>{{ unit.dispatched }}</td>
<td>{{ unit.arrived }}</td>
<td>{{ unit.in_service }}</td>
</tr>
</table>


    </td>
  </tr>
</table>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您的问题似乎在setInterval。当您致电getLocation时,它不需要()

i = 0;
app = new Vue({
  el: '#app',
  data: {
    events: []
  },
  methods: {
    getLocation: function () {
      var self = this;
      i+=1;
      self.events =  [1,2,3,i];
    }
  },
  created: function() {
    self = this;
    setInterval(self.getLocation, 1000);
  }
})

这是一个有效的演示:

https://codepen.io/egerrard/pen/EwLVNB