vue轮询方法及清除

<script>
  var Vue = new Vue({
    el: '#app',
    data: {
      timer: null,
    },
    created() {
		this.pollfun()
    },
    methods: {
      //轮询
      pollfun() {
        this.timer = window.setInterval(() => {
          setTimeout(() => {
            this.getDetes()
          }, 0)
        }, 3000)
      },
      //清除轮询
      clearfun() {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    //离开页面清除
    destroyed() {
      window.clearInterval(this.timer)
    }
  })
</script>

destroyed 是监听页面销毁钩子函数

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当使用 Vue.js 进行轮询访问后端接口时,你可以使用 `setInterval` 函数来定时发送请求。以下是一个简单的代码示例: ```javascript <template> <div> <p>{{ responseData }}</p> </div> </template> <script> export default { data() { return { responseData: null, intervalId: null, }; }, mounted() { this.startPolling(); }, methods: { startPolling() { this.intervalId = setInterval(() => { this.fetchData(); }, 5000); // 5秒钟发送一次请求,可以根据需求调整时间间隔 }, stopPolling() { clearInterval(this.intervalId); }, fetchData() { // 使用 axios 或其他 HTTP 库发送请求 // 在这里调用后端接口获取数据 axios.get('/api/data') .then(response => { this.responseData = response.data; }) .catch(error => { console.error(error); }); }, }, beforeDestroy() { this.stopPolling(); }, }; </script> ``` 在上述代码中,我们在组件的 `mounted` 钩子函数中调用 `startPolling` 方法来开始轮询。`startPolling` 方法使用 `setInterval` 函数来定时调用 `fetchData` 方法,该方法通过发送 HTTP 请求获取数据,并将返回的数据赋值给 `responseData` 变量。 当组件销毁时,我们使用 `beforeDestroy` 钩子函数调用 `stopPolling` 方法来停止轮询,使用 `clearInterval` 函数清除定时器。 请注意,上述代码中使用了 axios 库来发送 HTTP 请求,你可以根据自己的需求选择合适的库来进行请求。另外,这只是一个简单的示例,你可能需要根据你的具体场景进行适当的修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值