2025-07-31 10:54:04 +08:00
|
|
|
import { getImageMainColor } from '@/utils/tools';
|
|
|
|
|
|
2025-08-04 13:55:46 +08:00
|
|
|
const DEFAULT_COLOR = '#E6E6E8';
|
|
|
|
|
const pendingRequests = new Map<HTMLElement, Promise<string | void>>();
|
|
|
|
|
|
2025-07-31 10:54:04 +08:00
|
|
|
const imageMainColorDirective = {
|
|
|
|
|
mounted(el: HTMLElement, binding: any) {
|
2025-08-04 13:55:46 +08:00
|
|
|
updateColor(el, binding.value);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
updated(el: HTMLElement, binding: any) {
|
|
|
|
|
if (binding.value !== binding.oldValue) {
|
|
|
|
|
updateColor(el, binding.value);
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
beforeUnmount(el: HTMLElement) {
|
|
|
|
|
pendingRequests.delete(el);
|
2025-07-31 10:54:04 +08:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2025-08-04 13:55:46 +08:00
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 获取图片主色调指令
|
2025-07-31 10:54:04 +08:00
|
|
|
export default {
|
|
|
|
|
install(app: any) {
|
|
|
|
|
app.directive('image-main-color', imageMainColorDirective);
|
|
|
|
|
}
|
|
|
|
|
};
|