成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

從入門到架構:構建企業級 Vue 防重復提交體系

開發
今天,我將帶你構建一套生產級的重復提交防御體系,涵蓋從基礎到架構的全套方案。

作為經歷過大型項目洗禮的前端工程師,我深知重復提交問題絕非簡單的按鈕禁用就能解決。今天,我將帶你構建一套生產級的重復提交防御體系,涵蓋從基礎到架構的全套方案。

一、問題本質與解決方案矩陣

在深入代碼前,我們需要建立完整的認知框架:

問題維度

典型表現

解決方案層級

用戶行為

快速連續點擊

交互層防御

網絡環境

請求延遲導致的重復提交

網絡層防御

業務場景

多Tab操作相同資源

業務層防御

系統架構

分布式請求處理

服務端冪等設計

二、基礎防御層:用戶交互控制

1. 防抖方案

// 適合緊急修復線上問題
const debounceSubmit = (fn, delay = 600) => {
  let timer = null;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
};

適用場景:臨時熱修復、簡單表單。

2. 狀態變量方案(Vue經典模式)

<template>
  <button 
    @click="handleSubmit"
    :disabled="submitting"
    :class="{ 'opacity-50': submitting }"
  >
    <Spin v-if="submitting" class="mr-1"/>
    {{ submitting ? '提交中...' : '確認提交' }}
  </button>
</template>

<script>
export default {
  data: () => ({
    submitting: false
  }),
  methods: {
    async handleSubmit() {
      if (this.submitting) return;
      
      this.submitting = true;
      try {
        await this.$api.createOrder(this.form);
        this.$message.success('創建成功');
      } finally {
        this.submitting = false;
      }
    }
  }
}
</script>

優化技巧:

  • 使用finally確保狀態重置
  • 添加視覺反饋(禁用狀態+加載動畫)

三、工程化層:可復用方案

1. 高階函數封裝

// utils/submitGuard.js
export const withSubmitGuard = (fn) => {
  let isPending = false;
  
  return async (...args) => {
    if (isPending) {
      throw new Error('請勿重復提交');
    }
    
    isPending = true;
    try {
      return await fn(...args);
    } finally {
      isPending = false;
    }
  };
};

// 使用示例
const guardedSubmit = withSubmitGuard(payload => 
  axios.post('/api/order', payload)
);

2. Vue Mixin方案

// mixins/submitGuard.js
export default {
  data: () => ({
    $_submitGuard: new Set() // 支持多請求并發控制
  }),
  methods: {
    async $guardSubmit(requestKey, fn) {
      if (this.$_submitGuard.has(requestKey)) {
        throw new Error(`[${requestKey}] 請求已在進行中`);
      }
      
      this.$_submitGuard.add(requestKey);
      try {
        return await fn();
      } finally {
        this.$_submitGuard.delete(requestKey);
      }
    }
  }
}

// 組件中使用
await this.$guardSubmit('createOrder', () => (
  this.$api.createOrder(this.form)
));

3. 自定義指令方案(Vue2/Vue3通用)

// directives/v-submit-lock.js
const createSubmitLockDirective = (compiler) => ({
  [compiler === 'vue3' ? 'beforeMount' : 'inserted'](el, binding) {
    const {
      callback,
      loadingText = '處理中...',
      lockClass = 'submit-lock',
      lockAttribute = 'data-submitting'
    } = normalizeOptions(binding);
    
    const originalHTML = el.innerHTML;
    let isSubmitting = false;
    
    const handleClick = async (e) => {
      if (isSubmitting) {
        e.preventDefault();
        e.stopImmediatePropagation();
        return;
      }
      
      isSubmitting = true;
      el.setAttribute(lockAttribute, 'true');
      el.classList.add(lockClass);
      el.innerHTML = loadingText;
      
      try {
        await callback(e);
      } finally {
        isSubmitting = false;
        el.removeAttribute(lockAttribute);
        el.classList.remove(lockClass);
        el.innerHTML = originalHTML;
      }
    };
    
    el._submitLockHandler = handleClick;
    el.addEventListener('click', handleClick, true);
  },
  
  [compiler === 'vue3' ? 'unmounted' : 'unbind'](el) {
    el.removeEventListener('click', el._submitLockHandler);
  }
});

function normalizeOptions(binding) {
  if (typeof binding.value === 'function') {
    return { callback: binding.value };
  }
  
  return {
    callback: binding.value?.handler || binding.value?.callback,
    loadingText: binding.value?.loadingText,
    lockClass: binding.value?.lockClass,
    lockAttribute: binding.value?.lockAttribute
  };
}

// Vue2注冊
Vue.directive('submit-lock', createSubmitLockDirective('vue2'));

// Vue3注冊
app.directive('submit-lock', createSubmitLockDirective('vue3'));

使用示例:

<template>
  <!-- 基礎用法 -->
  <button v-submit-lock="handleSubmit">提交</button>
  
  <!-- 配置參數 -->
  <button
    v-submit-lock="{
      handler: submitPayment,
      loadingText: '支付中...',
      lockClass: 'payment-lock'
    }"
    class="btn-pay"
  >
    立即支付
  </button>
  
  <!-- 帶事件參數 -->
  <button
    v-submit-lock="(e) => handleSpecialSubmit(e, params)"
  >
    特殊提交
  </button>
</template>

指令優勢:

  • 完全解耦:與組件邏輯零耦合
  • 細粒度控制:可針對不同按鈕單獨配置
  • 框架無關:核心邏輯可移植到其他框架
  • 漸進增強:支持從簡單到復雜的各種場景

4. 組合式API方案(Vue3專屬)

// composables/useSubmitLock.ts
import { ref } from 'vue';

export function useSubmitLock() {
  const locks = ref<Set<string>>(new Set());
  
  const withLock = async <T>(
    key: string | symbol,
    fn: () => Promise<T>
  ): Promise<T> => {
    const lockKey = typeof key === 'symbol' ? key.description : key;
    
    if (locks.value.has(lockKey!)) {
      throw new Error(`操作[${String(lockKey)}]已在進行中`);
    }
    
    locks.value.add(lockKey!);
    try {
      return await fn();
    } finally {
      locks.value.delete(lockKey!);
    }
  };
  
  return { withLock };
}

// 組件中使用
const { withLock } = useSubmitLock();

const handleSubmit = async () => {
  await withLock('orderSubmit', async () => {
    await api.submitOrder(form.value);
  });
};

四、架構級方案:指令+攔截器聯合作戰

1. 智能請求指紋生成

// utils/requestFingerprint.js
import qs from 'qs';
import hash from 'object-hash';

const createFingerprint = (config) => {
  const { method, url, params, data } = config;
  
  const baseKey = `${method.toUpperCase()}|${url}`;
  const paramsKey = params ? qs.stringify(params, { sort: true }) : '';
  const dataKey = data ? hash.sha1(data) : '';
  
  return [baseKey, paramsKey, dataKey].filter(Boolean).join('|');
};

2. 增強版Axios攔截器

// services/api.js
const pendingRequests = new Map();

const requestInterceptor = (config) => {
  if (config.__retryCount) return config; // 重試請求放行
  
  const fingerprint = createFingerprint(config);
  const cancelSource = axios.CancelToken.source();
  
  // 中斷同類請求(可配置策略)
  if (pendingRequests.has(fingerprint)) {
    const strategy = config.duplicateStrategy || 'cancel'; // cancel|queue|ignore
    
    switch (strategy) {
      case 'cancel':
        pendingRequests.get(fingerprint).cancel(
          `[${fingerprint}] 重復請求已取消`
        );
        break;
      case 'queue':
        return new Promise((resolve) => {
          pendingRequests.get(fingerprint).queue.push(resolve);
        });
      case 'ignore':
        throw axios.Cancel(`[${fingerprint}] 重復請求被忽略`);
    }
  }
  
  config.cancelToken = cancelSource.token;
  pendingRequests.set(fingerprint, {
    cancel: cancelSource.cancel,
    queue: []
  });
  
  return config;
};

const responseInterceptor = (response) => {
  const fingerprint = createFingerprint(response.config);
  completeRequest(fingerprint);
  return response;
};

const errorInterceptor = (error) => {
  if (!axios.isCancel(error)) {
    const fingerprint = error.config && createFingerprint(error.config);
    fingerprint && completeRequest(fingerprint);
  }
  return Promise.reject(error);
};

const completeRequest = (fingerprint) => {
  if (pendingRequests.has(fingerprint)) {
    const { queue } = pendingRequests.get(fingerprint);
    if (queue.length > 0) {
      const nextResolve = queue.shift();
      nextResolve(axios.request(pendingRequests.get(fingerprint).config);
    } else {
      pendingRequests.delete(fingerprint);
    }
  }
};

3. 生產級Vue指令(增強版)

// directives/v-request.js
const STATE = {
  IDLE: Symbol('idle'),
  PENDING: Symbol('pending'),
  SUCCESS: Symbol('success'),
  ERROR: Symbol('error')
};

export default {
  beforeMount(el, { value }) {
    const {
      action,
      confirm = null,
      loadingClass = 'request-loading',
      successClass = 'request-success',
      errorClass = 'request-error',
      strategies = {
        duplicate: 'cancel', // cancel|queue|ignore
        error: 'reset' // reset|keep
      }
    } = parseOptions(value);
    
    let state = STATE.IDLE;
    let originalContent = el.innerHTML;
    
    const setState = (newState) => {
      state = newState;
      el.classList.remove(loadingClass, successClass, errorClass);
      
      switch (state) {
        case STATE.PENDING:
          el.classList.add(loadingClass);
          el.disabled = true;
          break;
        case STATE.SUCCESS:
          el.classList.add(successClass);
          el.disabled = false;
          break;
        case STATE.ERROR:
          el.classList.add(errorClass);
          el.disabled = strategies.error === 'keep';
          break;
        default:
          el.disabled = false;
      }
    };
    
    el.addEventListener('click', async (e) => {
      if (state === STATE.PENDING) {
        e.preventDefault();
        return;
      }
      
      try {
        if (confirm && !window.confirm(confirm)) return;
        
        setState(STATE.PENDING);
        await action(e);
        setState(STATE.SUCCESS);
      } catch (err) {
        setState(STATE.ERROR);
        throw err;
      }
    });
  }
};

function parseOptions(value) {
  if (typeof value === 'function') {
    return { action: value };
  }
  
  if (value && typeof value.action === 'function') {
    return value;
  }
  
  throw new Error('Invalid directive options');
}

4. 企業級使用示例

<template>
  <!-- 基礎用法 -->
  <button 
    v-request="submitForm"
    class="btn-primary"
  >
    提交訂單
  </button>
  
  <!-- 高級配置 -->
  <button
    v-request="{
      action: () => $api.pay(orderId),
      confirm: '確定支付嗎?',
      strategies: {
        duplicate: 'queue',
        error: 'keep'
      },
      loadingClass: 'payment-loading',
      successClass: 'payment-success'
    }"
    class="btn-pay"
  >
    <template v-if="$requestState?.isPending">
      <LoadingIcon /> 支付處理中
    </template>
    <template v-else>
      立即支付
    </template>
  </button>
</template>

<script>
export default {
  methods: {
    async submitForm() {
      const resp = await this.$api.submit({
        ...this.form,
        __duplicateStrategy: 'cancel' // 覆蓋全局策略
      });
      
      this.$emit('submitted', resp.data);
    }
  }
}
</script>

五、性能與安全增強建議

內存優化:

  • 使用WeakMap存儲請求上下文
  • 設置請求指紋TTL自動清理

異常監控:

// 在攔截器中添加監控點
const errorInterceptor = (error) => {
  if (axios.isCancel(error)) {
    trackDuplicateRequest(error.message);
  }
  // ...
};

服務端協同:

// 在請求頭添加冪等ID
axios.interceptors.request.use(config => {
  config.headers['X-Idempotency-Key'] = generateIdempotencyKey();
  return config;
});

六、如何選擇適合的方案?

初創項目:狀態變量 + 基礎指令

中臺系統:高階函數 + 攔截器基礎版

金融級應用:全鏈路防御體系 + 服務端冪等

特殊場景:

  • 支付場景:請求隊列 + 狀態持久化
  • 數據看板:取消舊請求策略

七、寫在最后

真正優秀的解決方案需要做到三個平衡:

  • 用戶體驗與系統安全的平衡
  • 開發效率與代碼質量的平衡
  • 前端控制與服務端協同的平衡

建議從簡單方案開始,隨著業務復雜度提升逐步升級防御體系。

責任編輯:趙寧寧 來源: 前端歷險記
相關推薦

2018-02-02 11:21:25

云計算標準和應用大會

2013-06-26 17:38:08

戴爾

2021-10-11 14:28:25

TypeScript企業級應用

2009-01-03 14:54:36

ibmdwWebSphere

2009-06-03 14:24:12

ibmdwWebSphere

2020-01-13 10:20:30

架構聊天架構百萬并發量

2024-05-20 11:23:18

2014-06-27 10:27:59

大數據體系

2021-03-04 12:57:02

PaaSSaaSIaaS

2012-02-15 13:08:43

2012-09-17 09:50:24

桌面虛擬化

2025-03-06 01:00:55

架構推送服務編程語言

2023-09-11 12:57:00

大數據大數據中臺

2011-12-02 09:02:32

2024-05-28 09:26:46

2009-12-09 08:49:13

JavaOracle

2020-07-31 07:45:43

架構系統企業級

2011-05-19 10:57:47

架構

2016-10-12 17:18:26

私有云持續交付華為

2014-09-09 14:10:01

企業級HadoopSpark
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 久久国产成人精品国产成人亚洲 | 97伦理| 国产精品99久久久久久大便 | 国产成人在线视频播放 | 黄色av网站在线免费观看 | 日韩毛片 | 精品综合 | 亚洲精品天堂 | 久久亚洲一区二区三区四区 | 99热在线观看精品 | 亚洲一区二区精品视频 | 九色在线视频 | 夜夜撸av| 九一国产精品 | 日韩视频精品在线 | 91精品国产91久久久久久不卞 | 亚洲国产黄色av | 精品一级| 国产高清亚洲 | 色综合99 | 久久精品久久综合 | 91精品国产91久久久久久最新 | 毛片毛片毛片毛片 | 成人性视频在线播放 | 草久在线视频 | 99久久99| 超级碰在线 | 啪啪精品 | 日本久草 | 一级毛片视频 | 黄色免费网站在线看 | 欧美精品一区免费 | 国产目拍亚洲精品99久久精品 | 天天久久 | 久久国产精品一区二区三区 | 日韩精品免费在线观看 | 极品的亚洲 | 免费观看毛片 | 欧美一级片黄色 | 色婷婷亚洲一区二区三区 | 国产精品91视频 |