当前位置:首页 > VUE

vue实现支付轮训

2026-01-19 10:15:06VUE

Vue 实现支付轮询

在 Vue 中实现支付轮询通常用于检查支付状态,直到支付成功或超时。以下是实现支付轮询的详细方法。

使用 setInterval 实现轮询

创建一个轮询函数,通过 setInterval 定期检查支付状态。当支付成功或达到最大轮询次数时,清除定时器。

methods: {
  startPaymentPolling(orderId, maxAttempts = 10, interval = 3000) {
    let attempts = 0;
    const poll = setInterval(async () => {
      attempts++;
      try {
        const response = await checkPaymentStatus(orderId);
        if (response.data.status === 'success') {
          clearInterval(poll);
          this.handlePaymentSuccess();
        } else if (attempts >= maxAttempts) {
          clearInterval(poll);
          this.handlePaymentTimeout();
        }
      } catch (error) {
        clearInterval(poll);
        this.handlePaymentError(error);
      }
    }, interval);
  },
  handlePaymentSuccess() {
    console.log('Payment succeeded');
  },
  handlePaymentTimeout() {
    console.log('Payment polling timed out');
  },
  handlePaymentError(error) {
    console.error('Payment polling error:', error);
  }
}

使用 setTimeout 递归实现轮询

递归调用 setTimeout 实现轮询,避免 setInterval 的潜在问题(如请求堆积)。

methods: {
  async pollPaymentStatus(orderId, attempts = 0, maxAttempts = 10, interval = 3000) {
    if (attempts >= maxAttempts) {
      this.handlePaymentTimeout();
      return;
    }
    try {
      const response = await checkPaymentStatus(orderId);
      if (response.data.status === 'success') {
        this.handlePaymentSuccess();
      } else {
        setTimeout(() => {
          this.pollPaymentStatus(orderId, attempts + 1, maxAttempts, interval);
        }, interval);
      }
    } catch (error) {
      this.handlePaymentError(error);
    }
  }
}

结合 Vue 生命周期管理轮询

在组件销毁时清除轮询,避免内存泄漏。

data() {
  return {
    pollingTimer: null
  };
},
methods: {
  startPaymentPolling(orderId) {
    this.pollingTimer = setInterval(async () => {
      const response = await checkPaymentStatus(orderId);
      if (response.data.status === 'success') {
        this.stopPaymentPolling();
        this.handlePaymentSuccess();
      }
    }, 3000);
  },
  stopPaymentPolling() {
    if (this.pollingTimer) {
      clearInterval(this.pollingTimer);
      this.pollingTimer = null;
    }
  }
},
beforeDestroy() {
  this.stopPaymentPolling();
}

使用第三方库(如 axios)实现轮询

结合 axios 发起请求,并处理取消逻辑。

import axios from 'axios';

data() {
  return {
    cancelToken: null
  };
},
methods: {
  startPaymentPolling(orderId) {
    const source = axios.CancelToken.source();
    this.cancelToken = source;
    const poll = async () => {
      try {
        const response = await checkPaymentStatus(orderId, {
          cancelToken: source.token
        });
        if (response.data.status === 'success') {
          this.handlePaymentSuccess();
        } else {
          setTimeout(poll, 3000);
        }
      } catch (error) {
        if (!axios.isCancel(error)) {
          this.handlePaymentError(error);
        }
      }
    };
    poll();
  },
  stopPaymentPolling() {
    if (this.cancelToken) {
      this.cancelToken.cancel('Polling stopped by user');
    }
  }
}

优化轮询逻辑

添加延迟增长策略(如指数退避),减少不必要的请求。

vue实现支付轮训

methods: {
  async pollPaymentStatus(orderId, attempts = 0, maxAttempts = 10, delay = 1000) {
    if (attempts >= maxAttempts) {
      this.handlePaymentTimeout();
      return;
    }
    try {
      const response = await checkPaymentStatus(orderId);
      if (response.data.status === 'success') {
        this.handlePaymentSuccess();
      } else {
        const nextDelay = Math.min(delay * 2, 10000); // 上限 10 秒
        setTimeout(() => {
          this.pollPaymentStatus(orderId, attempts + 1, maxAttempts, nextDelay);
        }, delay);
      }
    } catch (error) {
      this.handlePaymentError(error);
    }
  }
}

关键点总结

  • 轮询方式选择setInterval 简单但需手动清理,递归 setTimeout 更灵活。
  • 生命周期管理:确保组件销毁时清除轮询,避免内存泄漏。
  • 错误处理:捕获网络错误和超时情况,提供用户反馈。
  • 性能优化:通过指数退避等策略减少无效请求。

标签: vue
分享给朋友:

相关文章

vue实现增删改

vue实现增删改

Vue 实现增删改查功能 Vue.js 是一个流行的前端框架,用于构建用户界面。以下是使用 Vue.js 实现增删改查(CRUD)功能的方法。 数据初始化 在 Vue 实例的 data 中初始化一个…

vue实现图片分析

vue实现图片分析

Vue 实现图片分析的方法 在 Vue 中实现图片分析通常涉及图片上传、预览、后端交互以及分析结果展示等功能。以下是几种常见的实现方式: 使用 HTML5 File API 和 Canvas 进行前…

vue实现购物按钮

vue实现购物按钮

Vue 购物按钮实现方法 基础按钮实现 使用 Vue 的模板语法创建基础按钮组件,绑定点击事件处理购物逻辑: <template> <button @click="addToC…

vue实现递归

vue实现递归

Vue 实现递归组件的方法 在 Vue 中实现递归组件通常用于处理树形结构数据(如菜单、评论列表、文件目录等)。以下是具体实现方法: 定义递归组件 通过 name 选项让组件可以递归调用自身:…

vue 实现列表

vue 实现列表

Vue 实现列表的方法 在 Vue 中实现列表通常使用 v-for 指令,结合数组或对象数据渲染动态列表。以下是几种常见的实现方式: 基础列表渲染 使用 v-for 指令遍历数组,渲染列表项。ite…

vue实现换行

vue实现换行

Vue 中实现换行的几种方法 在 Vue 中实现换行可以通过多种方式,具体取决于使用场景和需求。以下是常见的几种方法: 使用 HTML 的 <br> 标签 在模板中直接使用 <br…