八個超級實用的前端代碼片段,總要用得上的!
今天給大家分享一些在前端開發中,比較實用的代碼片段,希望大家能用得上!
1、檢測點擊元素外部
比如你想要點擊彈窗外部去關閉彈窗,或者 Vue 的自定義指令 clickoutside,都是利用了下面這個代碼片段。
圖片
2、一次性事件監聽
相信大家都用過 addEventListener吧?你監聽后想要解除需要用到 removeEventListener,但是如果你只是想要一次性監聽的話,可以傳入第三個參數。
圖片
3、手動解除事件監聽
還是 addEventListener,如果你不想使用 removeEventListener 去解除監聽的話,你也可以使用 AbortController + signal 去進行手動解除監聽。
圖片
4、控制并發數
現在前端中使用異步操作已經是常態,更別說異步請求了,而當異步請求并發量比較高的時候,為了節約網絡資源提高用戶體驗,我們需要控制并發數。
圖片
limitFn 的具體實現我放在下面了。
const limitFn = (limit) => {
const queue = [];
let activeCount = 0;
const next = () => {
activeCount--;
if (queue.length > 0) {
queue.shift()();
}
};
const run = async (fn, resolve, ...args) => {
activeCount++;
const result = (async () => fn(...args))();
try {
const res = await result;
resolve(res);
} catch { }
next();
};
const enqueue = (fn, resolve, ...args) => {
queue.push(run.bind(null, fn, resolve, ...args));
if (activeCount < limit && queue.length > 0) {
queue.shift()();
}
};
const generator = (fn, ...args) =>
new Promise((resolve) => {
enqueue(fn, resolve, ...args);
});
return generator;
};
5、生成唯一ID
也就是生成一個唯一的 uuid,其實現在很多庫都可以做,比如 lodash,當然你也可以自己寫一個。
const uuid = (a) =>
a
? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16)
: ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid)
6、格式化時分秒
如果你想要把時間格式化成 HH:mm:ss 這樣的話。
const formatSeconds = (s) =>
[parseInt(s / 60 / 60), parseInt((s / 60) % 60), parseInt(s % 60)]
.join(':')
.replace(/\b(\d)\b/g, '0$1')
7、提取 URL 的參數
可以將 URL 上的參數提取出來,變成一個對象。
const getUrlParams = (query) =>
Array.from(new URLSearchParams(query)).reduce(
(p, [k, v]) =>
Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),
{}
)
8、打開彈窗時禁止頁面滾動
當我們打開彈窗時,我們不希望整個頁面還能滾動,那么可以在打開彈窗時去設置頁面的滾動樣式。