2017-10-09 76 views
0

每10秒我查詢我的數據庫最新的火災呼叫。我做app.events = data.calls但我的數據不刷新。我使用每10秒調用一次的相同函數初始化數據。我看到桌子了。我如何使用數組替換Vue中的數組?在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> 
+0

https://stackoverflow.com/help/mcve – thanksd

回答

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

+0

也似乎並不修理它。請參閱https://codepen.io/policevideorequests/pen/GMdpZr,其中最後一個塊只更新爲1而不是2,3,4等 –

+0

啊我看到你在找什麼。是的,仍然工作正常,你只需要更新你的setInterval。我已經更新了我的答案。另請參閱https://codepen.io/egerrard/pen/EwLVNB –

+0

嘗試'setInterval(self.getLocation,1000);'。 Vue將'this'用於方法。 –

相關問題