Implementación de la interfaz de sondeo Vue

En los proyectos, a menudo necesitamos implementar datos de actualización de la interfaz de solicitud de sondeo cada pocos segundos

SetInterval se usa generalmente, pero debe tenerse en cuenta que simplemente usarlo hará que la página se congele, así que asegúrese de borrar el temporizador

setInterval no borrará la cola del temporizador. Cada vez que se ejecute repetidamente, hará que el temporizador se superponga y eventualmente congele su página web.
Pero setTimeout viene con un temporizador claro

mounted () {
    
    
    const timer = window.setInterval(() => {
    
    
      setTimeout(function () {
    
    
      // chooseProduct 自己封装的axios请求 
        chooseProduct({
    
    
          'promptKey': 'selectitem',
          'serialNum': '000'
        }).then(res => {
    
    
           //视情况而定
          if (String(res.data.success) === 'true') {
    
    
            // 这里可以写一些中止轮询的条件 比如res.data.success返回true时  
            clearInterval(timer)
          }
        })
      }, 0)
    }, 2000)
    // 清除定时器
    this.$once('hook:beforeDestroy', () => {
    
    
      clearInterval(timer)
    })
  }


Paquete

// polling-utils.js

/**
     * @descripting 轮询功能
     * @param {
    
    String} type 请求类型
     * @param {
    
    String} url 地址 
     * @param {
    
    Object} data 请求数据 
     * @param {
    
    Number} delay 轮询间隔时间
     */
    export default function polling(type, url, data, delay = 1000) {
    
    
        return new Promise((resolve, reject) =>{
    
    
            ajax[type](url, data).then(res => {
    
    
                if (res.data === 'polling') {
    
      // 这个继续进行轮询的条件,需要根据自己的需要修改
                    setTimeout(() => {
                        resolve(polling(type, url, data, delay));
                    }, delay)
                } else {
    
    
                   resolve(res);
               }
           })
       })
    }

utilizar

import polling from 'utils/polling-utils';

polling('post', url, data).then(res => {
    
     console.log(res) })

Supongo que te gusta

Origin blog.csdn.net/weixin_46034375/article/details/109078287
Recomendado
Clasificación