最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

前端使用次數(shù)最多的一些實(shí)用工具封裝

 更新時(shí)間:2026年05月28日 10:30:06   作者:一支魚  
在前端開發(fā)中,封裝是實(shí)現(xiàn)代碼復(fù)用、提高可維護(hù)性的重要手段,這篇文章主要介紹了前端使用次數(shù)最多的一些實(shí)用工具封裝,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下

1. 數(shù)據(jù)處理工具

1.1 數(shù)組去重并保持順序

  • 功能分析:去除數(shù)組中的重復(fù)元素,并保持元素的原始順序。在處理需要保持特定順序的數(shù)據(jù),如用戶操作歷史記錄等場景中很有用。
  • 代碼實(shí)現(xiàn)
const arrayUtils = {
    uniqueArrayPreserveOrder: function <T>(arr: T[]): T[] {
        const seen: { [key: string]: boolean } = {};
        return arr.filter((item) => {
            const key = typeof item === 'object'? JSON.stringify(item) : item;
            if (seen[key]) {
                return false;
            }
            seen[key] = true;
            return true;
        });
    }
};
  • 使用示例
const arrWithDuplicates = [1, { value: 'a' }, 2, { value: 'a' }, 3];
const uniqueArr = arrayUtils.uniqueArrayPreserveOrder(arrWithDuplicates);
console.log(uniqueArr); 
// 輸出: [1, { value: 'a' }, 2, 3]

1.2 數(shù)組分組

  • 功能分析:根據(jù)給定的分組函數(shù),將數(shù)組元素分成不同的組。常用于數(shù)據(jù)統(tǒng)計(jì)、分類展示等場景,比如將訂單按月份分組。
  • 代碼實(shí)現(xiàn)
const arrayUtils = {
    groupArray: function <T, K>(arr: T[], keySelector: (item: T) => K): { [key: string]: T[] } {
        return arr.reduce((acc, item) => {
            const key = keySelector(item).toString();
            if (!acc[key]) {
                acc[key] = [];
            }
            acc[key].push(item);
            return acc;
        }, {} as { [key: string]: T[] });
    }
};
  • 使用示例
const orders = [
    { id: 1, date: new Date('2024 - 01 - 10'), amount: 100 },
    { id: 2, date: new Date('2024 - 02 - 15'), amount: 200 },
    { id: 3, date: new Date('2024 - 01 - 20'), amount: 150 }
];
const groupedOrders = arrayUtils.groupArray(orders, order => order.date.getMonth());
console.log(groupedOrders); 
// 輸出: { '0': [ { id: 1, date: 2024 - 01 - 10, amount: 100 }, { id: 3, date: 2024 - 01 - 20, amount: 150 } ], '1': [ { id: 2, date: 2024 - 02 - 15, amount: 200 } ] }

2. DOM 操作工具

2.1 獲取元素距離視口頂部的距離

  • 功能分析:獲取元素相對(duì)于瀏覽器視口頂部的距離,對(duì)于實(shí)現(xiàn)視口相關(guān)的交互,如元素進(jìn)入視口時(shí)觸發(fā)動(dòng)畫等功能很重要。
  • 代碼實(shí)現(xiàn)
const domUtils = {
    getElementTopRelativeToViewport: function (element: HTMLElement): number {
        const rect = element.getBoundingClientRect();
        return rect.top + window.pageYOffset;
    }
};
  • 使用示例
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF - 8">
    <title>DOM Utils Example</title>
    <style>
        #testDiv {
            margin - top: 200px;
        }
    </style>
</head>

<body>
    <div id="testDiv">Test Div</div>
    <script lang="ts">
        const testDiv = document.getElementById('testDiv') as HTMLElement;
        const divTop = domUtils.getElementTopRelativeToViewport(testDiv);
        console.log(divTop); 
    </script>
</body>

</html>

2.2 批量添加事件監(jiān)聽器

  • 功能分析:為多個(gè)元素一次性添加相同類型的事件監(jiān)聽器,簡化事件綁定操作,提高代碼效率。適用于批量處理同類元素的交互,如按鈕組的點(diǎn)擊事件。
  • 代碼實(shí)現(xiàn)
const domUtils = {
    addEventListeners: function (selector: string, eventType: string, handler: (event: Event) => void) {
        const elements = document.querySelectorAll(selector);
        elements.forEach((element) => {
            element.addEventListener(eventType, handler);
        });
    }
};
  • 使用示例
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF - 8">
    <title>DOM Utils Example</title>
</head>

<body>
    <button class="actionButton">Button 1</button>
    <button class="actionButton">Button 2</button>
    <script lang="ts">
        domUtils.addEventListeners('.actionButton', 'click', (event) => {
            console.log('Button clicked');
        });
    </script>
</body>

</html>

3. 網(wǎng)絡(luò)請(qǐng)求工具(基于 Axios)

3.1 帶重試機(jī)制的網(wǎng)絡(luò)請(qǐng)求封裝

  • 功能分析:在網(wǎng)絡(luò)請(qǐng)求失敗時(shí),自動(dòng)進(jìn)行重試,提高請(qǐng)求的成功率。對(duì)于不穩(wěn)定的網(wǎng)絡(luò)環(huán)境或偶爾出現(xiàn)的短暫故障很實(shí)用。
  • 代碼實(shí)現(xiàn)
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

interface ResponseData<T> {
    code: number;
    message: string;
    data: T;
}

const httpUtils: {
    instance: AxiosInstance;
    init: () => void;
    get: <T>(url: string, params?: object, retries = 3): Promise<T>;
    post: <T>(url: string, data?: object, retries = 3): Promise<T>;
    put: <T>(url: string, data?: object, retries = 3): Promise<T>;
    delete: <T>(url: string, retries = 3): Promise<T>;
} = {
    instance: axios.create({
        baseURL: 'https://your - api - base - url.com',
        timeout: 5000,
        headers: {
            'Content - Type': 'application/json'
        }
    }),
    init: function () {
        this.instance.interceptors.request.use((config: AxiosRequestConfig) => {
            const token = localStorage.getItem('token');
            if (token) {
                config.headers.Authorization = `Bearer ${token}`;
            }
            return config;
        }, error => {
            return Promise.reject(error);
        });

        this.instance.interceptors.response.use((response: AxiosResponse<ResponseData<any>>) => {
            if (response.data.code!== 200) {
                throw new Error(response.data.message);
            }
            return response.data.data;
        }, error => {
            console.error('Request error:', error);
            return Promise.reject(error);
        });
    },
    get: async function <T>(url: string, params: object = {}, retries = 3): Promise<T> {
        let attempt = 0;
        while (attempt < retries) {
            try {
                const response = await this.instance.get(url, { params });
                return response.data;
            } catch (error) {
                attempt++;
                if (attempt === retries) {
                    throw error;
                }
            }
        }
        throw new Error('Max retries reached');
    },
    post: async function <T>(url: string, data: object = {}, retries = 3): Promise<T> {
        let attempt = 0;
        while (attempt < retries) {
            try {
                const response = await this.instance.post(url, data);
                return response.data;
            } catch (error) {
                attempt++;
                if (attempt === retries) {
                    throw error;
                }
            }
        }
        throw new Error('Max retries reached');
    },
    put: async function <T>(url: string, data: object = {}, retries = 3): Promise<T> {
        let attempt = 0;
        while (attempt < retries) {
            try {
                const response = await this.instance.put(url, data);
                return response.data;
            } catch (error) {
                attempt++;
                if (attempt === retries) {
                    throw error;
                }
            }
        }
        throw new Error('Max retries reached');
    },
    delete: async function <T>(url: string, retries = 3): Promise<T> {
        let attempt = 0;
        while (attempt < retries) {
            try {
                const response = await this.instance.delete(url);
                return response.data;
            } catch (error) {
                attempt++;
                if (attempt === retries) {
                    throw error;
                }
            }
        }
        throw new Error('Max retries reached');
    }
};

httpUtils.init();
export default httpUtils;
  • 使用示例
import httpUtils from './httpUtils';

// GET請(qǐng)求
httpUtils.get('/api/data', { param1: 'value1' }, 5)
  .then(data => {
        console.log(data);
    })
  .catch(error => {
        console.error(error);
    });

4. 存儲(chǔ)管理工具

4.1 本地存儲(chǔ)有效期管理

  • 功能分析:為本地存儲(chǔ)的數(shù)據(jù)設(shè)置有效期,過期后自動(dòng)刪除。適用于存儲(chǔ)一些臨時(shí)數(shù)據(jù),如用戶登錄的短期憑證等。
  • 代碼實(shí)現(xiàn)
const storageUtils = {
    setLocalStorageWithExpiry: function (key: string, value: any, durationInMinutes: number) {
        const data = {
            value,
            expiry: new Date().getTime() + durationInMinutes * 60 * 1000
        };
        localStorage.setItem(key, JSON.stringify(data));
    },
    getLocalStorageWithExpiry: function (key: string): any {
        const item = localStorage.getItem(key);
        if (!item) {
            return null;
        }
        const { value, expiry } = JSON.parse(item);
        if (new Date().getTime() > expiry) {
            localStorage.removeItem(key);
            return null;
        }
        return value;
    }
};
  • 使用示例
storageUtils.setLocalStorageWithExpiry('tempToken', 'abc123', 30); 
const tempToken = storageUtils.getLocalStorageWithExpiry('tempToken');
console.log(tempToken); 

5. 日期時(shí)間處理工具

5.1 獲取指定月份的所有日期

  • 功能分析:獲取指定年份和月份的所有日期,在日歷組件開發(fā)等場景中經(jīng)常用到。
  • 代碼實(shí)現(xiàn)
const dateTimeUtils = {
    getDatesOfMonth: function (year: number, month: number): Date[] {
        const dates: Date[] = [];
        const lastDay = new Date(year, month + 1, 0).getDate();
        for (let day = 1; day <= lastDay; day++) {
            dates.push(new Date(year, month, day));
        }
        return dates;
    }
};
  • 使用示例
const dates = dateTimeUtils.getDatesOfMonth(2024, 9); 
dates.forEach(date => {
    console.log(date.toISOString().split('T')[0]);
});
// 輸出2024年10月的所有日期

5.2 計(jì)算兩個(gè)日期之間的工作日天數(shù)

  • 功能分析:計(jì)算兩個(gè)日期之間的工作日天數(shù),不包括周末。在項(xiàng)目進(jìn)度管理、考勤計(jì)算等場景中有實(shí)際應(yīng)用。
  • 代碼實(shí)現(xiàn)
const dateTimeUtils = {
    getWorkingDaysBetween: function (startDate: Date, endDate: Date): number {
        let currentDate = new Date(startDate);
        let workingDays = 0;
        while (currentDate <= endDate) {
            const dayOfWeek = currentDate.getDay();
            if (dayOfWeek!== 0 && dayOfWeek!== 6) {
                workingDays++;
            }
            currentDate.setDate(currentDate.getDate() + 1);
        }
        return workingDays;
    }
};
  • 使用示例
const start = new Date('2024 - 10 - 01');
const end = new Date('2024 - 10 - 10');
const workingDays = dateTimeUtils.getWorkingDaysBetween(start, end);
console.log(workingDays); 
// 計(jì)算2024年10月1日到10月10日之間的工作日天數(shù)

總結(jié) 

到此這篇關(guān)于前端使用次數(shù)最多的一些實(shí)用工具封裝的文章就介紹到這了,更多相關(guān)前端工具封裝內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

扎赉特旗| 禹州市| 建德市| 京山县| 普兰店市| 泸西县| 沭阳县| 上思县| 西乌| 长宁县| 南投市| 大石桥市| 湛江市| 额敏县| 梅河口市| 乐至县| 教育| 彰化市| 沧州市| 同心县| 塔城市| 无棣县| 教育| 化州市| 北辰区| 江北区| 大埔县| 高邑县| 南阳市| 台南市| 天全县| 克东县| 梧州市| 鹤岗市| 郸城县| 大兴区| 宜宾市| 沿河| 龙泉市| 安塞县| 沭阳县|