偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

從入門到架構(gòu):構(gòu)建企業(yè)級 Vue 防重復(fù)提交體系

開發(fā)
今天,我將帶你構(gòu)建一套生產(chǎn)級的重復(fù)提交防御體系,涵蓋從基礎(chǔ)到架構(gòu)的全套方案。

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

一、問題本質(zhì)與解決方案矩陣

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

問題維度

典型表現(xiàn)

解決方案層級

用戶行為

快速連續(xù)點擊

交互層防御

網(wǎng)絡(luò)環(huán)境

請求延遲導(dǎo)致的重復(fù)提交

網(wǎng)絡(luò)層防御

業(yè)務(wù)場景

多Tab操作相同資源

業(yè)務(wù)層防御

系統(tǒng)架構(gòu)

分布式請求處理

服務(wù)端冪等設(shè)計

二、基礎(chǔ)防御層:用戶交互控制

1. 防抖方案

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

適用場景:臨時熱修復(fù)、簡單表單。

2. 狀態(tài)變量方案(Vue經(jīng)典模式)

<template>
  <button 
    @click="handleSubmit"
    :disabled="submitting"
    :class="{ 'opacity-50': submitting }"
  >
    <Spin v-if="submitting" class="mr-1"/>
    {{ submitting ? '提交中...' : '確認(rèn)提交' }}
  </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('創(chuàng)建成功');
      } finally {
        this.submitting = false;
      }
    }
  }
}
</script>

優(yōu)化技巧:

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

三、工程化層:可復(fù)用方案

1. 高階函數(shù)封裝

// utils/submitGuard.js
export const withSubmitGuard = (fn) => {
  let isPending = false;
  
  return async (...args) => {
    if (isPending) {
      throw new Error('請勿重復(fù)提交');
    }
    
    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() // 支持多請求并發(fā)控制
  }),
  methods: {
    async $guardSubmit(requestKey, fn) {
      if (this.$_submitGuard.has(requestKey)) {
        throw new Error(`[${requestKey}] 請求已在進(jìn)行中`);
      }
      
      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>
  <!-- 基礎(chǔ)用法 -->
  <button v-submit-lock="handleSubmit">提交</button>
  
  <!-- 配置參數(shù) -->
  <button
    v-submit-lock="{
      handler: submitPayment,
      loadingText: '支付中...',
      lockClass: 'payment-lock'
    }"
    class="btn-pay"
  >
    立即支付
  </button>
  
  <!-- 帶事件參數(shù) -->
  <button
    v-submit-lock="(e) => handleSpecialSubmit(e, params)"
  >
    特殊提交
  </button>
</template>

指令優(yōu)勢:

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

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)}]已在進(jìn)行中`);
    }
    
    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);
  });
};

四、架構(gòu)級方案:指令+攔截器聯(lián)合作戰(zhàn)

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}] 重復(fù)請求已取消`
        );
        break;
      case 'queue':
        return new Promise((resolve) => {
          pendingRequests.get(fingerprint).queue.push(resolve);
        });
      case 'ignore':
        throw axios.Cancel(`[${fingerprint}] 重復(fù)請求被忽略`);
    }
  }
  
  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. 生產(chǎn)級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. 企業(yè)級使用示例

<template>
  <!-- 基礎(chǔ)用法 -->
  <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>

五、性能與安全增強建議

內(nèi)存優(yōu)化:

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

異常監(jiān)控:

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

服務(wù)端協(xié)同:

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

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

初創(chuàng)項目:狀態(tài)變量 + 基礎(chǔ)指令

中臺系統(tǒng):高階函數(shù) + 攔截器基礎(chǔ)版

金融級應(yīng)用:全鏈路防御體系 + 服務(wù)端冪等

特殊場景:

  • 支付場景:請求隊列 + 狀態(tài)持久化
  • 數(shù)據(jù)看板:取消舊請求策略

七、寫在最后

真正優(yōu)秀的解決方案需要做到三個平衡:

  • 用戶體驗與系統(tǒng)安全的平衡
  • 開發(fā)效率與代碼質(zhì)量的平衡
  • 前端控制與服務(wù)端協(xié)同的平衡

建議從簡單方案開始,隨著業(yè)務(wù)復(fù)雜度提升逐步升級防御體系。

責(zé)任編輯:趙寧寧 來源: 前端歷險記
相關(guān)推薦

2018-02-02 11:21:25

云計算標(biāo)準(zhǔn)和應(yīng)用大會

2013-06-26 17:38:08

戴爾

2021-10-11 14:28:25

TypeScript企業(yè)級應(yīng)用

2009-01-03 14:54:36

ibmdwWebSphere

2009-06-03 14:24:12

ibmdwWebSphere

2020-01-13 10:20:30

架構(gòu)聊天架構(gòu)百萬并發(fā)量

2024-05-20 11:23:18

2014-06-27 10:27:59

大數(shù)據(jù)體系

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

架構(gòu)推送服務(wù)編程語言

2023-09-11 12:57:00

大數(shù)據(jù)大數(shù)據(jù)中臺

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

架構(gòu)系統(tǒng)企業(yè)級

2011-05-19 10:57:47

架構(gòu)

2016-10-12 17:18:26

私有云持續(xù)交付華為

2014-09-09 14:10:01

企業(yè)級HadoopSpark
點贊
收藏

51CTO技術(shù)棧公眾號