我在Django模板中有一个Vue.js视图。Vue从Django Rest Framework端点提取要在视图中显示的数据。我的代码如下:
const app = new Vue({
el: '#app',
delimiters: ["[%", "%]"],
data: {
dedicated_server: [],
},
created() {
fetch('/api/dedicated-server/{{ object.id }}/')
.then(response => response.json())
.then(json => {
this.dedicated_server = json;
})
},
updated() {
/* TODO: Try and limit the number of requests to the API */
fetch('/api/dedicated-server/{{ object.id }}/')
.then(response => response.json())
.then(json => {
this.dedicated_server = json
})
},
});
如您所见,我有一个更新的方法,它轮询Restful端点,以便在数据更改时更新页面。这一切都很好,但似乎每秒钟轮询Restful端点3至5次。这是很好的开发,但如果我有100人访问这个页面,那么它将杀死我的服务器与请求。
是否有办法限制Vue.js检查的次数,以查看数据是否已经更新?如果你能说每5秒检查一次,那就太好了。
发布于 2018-12-08 11:51:39
您可以使用setInterval
每5秒运行一次。在created
中设置它,您不需要担心updated
。
setInterval(() =>
fetch('/api/dedicated-server/{{ object.id }}/')
.then(response => response.json())
.then(json => {
this.dedicated_server = json;
}),
5000);
https://stackoverflow.com/questions/53682123
复制相似问题