【问题标题】:call method every so often vue js每隔一段时间调用方法vue js
【发布时间】:2026-01-01 16:30:01
【问题描述】:

我需要经常调用一个函数,我想要的是每隔一段时间更新一次数据,因此我需要调用那个方法,我使用的是 vue js。

同理我想知道vue js的哪个属性定位,谢谢,我会调查所有的cmets

我需要每 30 秒调用一次 'listar()' 方法

<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>

这对我不起作用

setTimeout(() => {
         //
}, 300)

升级 1

这段代码实际上对我有用,但问题是——在你切换到另一个页面后它会继续运行,因为它是一个单页应用程序。

我正在使用 clearInterval () 但它不起作用,即使我更改页面(组件),该方法也会继续运行。 只在我第一次进入另一个页面时清除清除,然后不再

参考-->https://renatello.com/vue-js-polling-using-setinterval/

<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
  • 更新我的问题,感谢您的评论,现在我遇到的问题是,尽管更改了页面,该方法仍在运行,它是一个 SPA 应用程序。

标签: javascript vue.js vue-component vuetify.js


【解决方案1】:

就像 ittus 说的,你应该使用setInterval

setInterval(() => {
    // call listen()
}, 30 * 1000);

setInterval 返回一个对象,您可以将其传递给clearInterval 以停止调用listen。

但是,如果您想考虑请求的时间,您也可以在(承诺)请求末尾的 .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没多大关系

【讨论】:

  • 更新我的问题,感谢您的评论,现在我遇到的问题是,尽管更改了页面,该方法仍在运行,它是一个 SPA 应用程序。