Javascript 经常调用方法vue js
我需要每隔一段时间调用一个函数,我想要的是每隔一段时间更新数据,因为这个原因我需要调用这个方法,我使用的是vue js 同样,我想知道vue js的哪个属性可以找到它,谢谢,我会调查所有的评论 我需要每30秒调用一次'listar'方法Javascript 经常调用方法vue js,javascript,vue.js,vue-component,vuetify.js,Javascript,Vue.js,Vue Component,Vuetify.js,我需要每隔一段时间调用一个函数,我想要的是每隔一段时间更新数据,因为这个原因我需要调用这个方法,我使用的是vue js 同样,我想知道vue js的哪个属性可以找到它,谢谢,我会调查所有的评论 我需要每30秒调用一次'listar'方法 <script> export default { methods: { listar(){ let me=this; me.mesas=[];
<script>
export default {
methods: {
listar(){
let me=this;
me.mesas=[];
axios.get('api/mesas/ListarTodos').then(function(response){
//console.log(response);
me.mesas=response.data;
me.loading=false;
}).catch(function(error){
console.log(error);
});
},
}
</script>
升级1
这段代码实际上对我有用,但问题是——在切换到另一个页面后,它将继续运行,因为它是一个单页面应用程序
我正在使用clearInterval,但它不起作用,即使我更改了页面组件,该方法仍保持运行。
清除只在我第一次进入另一个页面时清除,然后不再清除
参考->
正如ittus所说,您应该使用setInterval: setInterval返回一个可以传递给clearInterval以停止调用listen的对象 但是,如果要考虑请求的时间,也可以在promise请求末尾的.finally块中使用setTimeout:
axios.get('api/mesas/ListarTodos').then(function(response){
//console.log(response);
me.mesas=response.data;
me.loading=false;
}).catch(function(error){
console.log(error);
}).finally(function(){
setTimeout(/*call listen in a function*/, 30 * 1000);
});
无论如何,它与vuejs没有多大关系您可以使用setIntervaluate更新我的问题,谢谢您的评论,现在我的问题是,尽管更改了页面,但该方法仍在运行,这是一个SPA应用程序。更新我的问题,谢谢您的评论,现在的问题是,尽管更改了页面,但该方法仍在运行,这是一个SPA应用程序。
<script>
import axios from 'axios'
export default {
data () {
return {
polling: null,
},
methods: {
listar(){
let me=this;
me.mesas=[];
axios.get('api/mesas/ListarTodos').then(function(response){
//console.log(response);
me.mesas=response.data;
me.loading=false;
}).catch(function(error){
console.log(error);
});
pollData () {
this.polling = setInterval(() => {
this.listar();
}, 3000) },
},
created () {
this.pollData()
},
beforeDestroy () {
clearInterval(this.polling)
},
}
</script>
setInterval(() => {
// call listen()
}, 30 * 1000);
axios.get('api/mesas/ListarTodos').then(function(response){
//console.log(response);
me.mesas=response.data;
me.loading=false;
}).catch(function(error){
console.log(error);
}).finally(function(){
setTimeout(/*call listen in a function*/, 30 * 1000);
});