我有一个Websocket连接(socket
),客户端应使用该连接定期更新app.value
。我需要在特定的div可见时定期调用send()函数,并在不可见时停止调用。我该怎么做?
<div id="app">
<div v-if="visible">
{{value}}
/* Periodically call send() here while this renders - how? */
</div>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
visible: false,
value: "Not loaded yet",
},
methods : {
send: function (type, data) {
socket.send("update");
}
}
});
/* the app.value update is already handled */
</script>
答案 0 :(得分:0)
我遵循了ippis和Mark_Ms的建议,并在代码中实现了更改app.value
变量的功能:
socket.onmessage = function(e) {
var packet = JSON.parse(e.data);
var type = packet["type"]
var data = packet["data"]
if (type=="info") {
if (app.value!==null) {
clearInterval(app.watcher)
}
app.value = data
app.watcher = setInterval(send, 1000)
}
}