Files
lingji-work-fe/src/directives/getImageMainColor.ts

52 lines
1.2 KiB
TypeScript

import { getImageMainColor } from '@/utils/tools';
const DEFAULT_COLOR = '#E6E6E8';
const pendingRequests = new Map<HTMLElement, Promise<string | void>>();
const imageMainColorDirective = {
mounted(el: HTMLElement, binding: any) {
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);
}
};