perf: 修改获取图片主色调指令逻辑

This commit is contained in:
rd
2025-08-04 13:55:46 +08:00
parent abea67be9c
commit 759c8cfbdc
4 changed files with 46 additions and 20 deletions

View File

@ -1,24 +1,49 @@
import { getImageMainColor } from '@/utils/tools';
// 创建图片主色调指令
const DEFAULT_COLOR = '#E6E6E8';
const pendingRequests = new Map<HTMLElement, Promise<string | void>>();
const imageMainColorDirective = {
mounted(el: HTMLElement, binding: any) {
const imageUrl = binding.value;
if (!imageUrl) return;
getImageMainColor(imageUrl)
.then(color => {
el.style.backgroundColor = color;
})
.catch(error => {
console.error('获取图片主色调失败:', error);
// 设置默认背景色
el.style.backgroundColor = '#E6E6E8';
});
updateColor(el, binding.value);
},
updated(el: HTMLElement, binding: any) {
if (binding.value !== binding.oldValue) {
updateColor(el, binding.value);
}
},
beforeUnmount(el: HTMLElement) {
pendingRequests.delete(el);
}
};
function updateColor(el: HTMLElement, imageUrl: string) {
if (!imageUrl) {
el.style.backgroundColor = DEFAULT_COLOR;
return;
}
// 创建新的请求
const request = getImageMainColor(imageUrl)
.then(color => {
if (pendingRequests.get(el) === request) {
el.style.backgroundColor = color;
pendingRequests.delete(el);
}
return color;
})
.catch(error => {
console.error('获取图片主色调失败:', error);
el.style.backgroundColor = DEFAULT_COLOR;
pendingRequests.delete(el);
});
pendingRequests.set(el, request);
}
// 获取图片主色调指令
export default {
install(app: any) {
app.directive('image-main-color', imageMainColorDirective);