perf: 修改获取图片主色调指令逻辑
This commit is contained in:
@ -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);
|
||||
|
||||
Reference in New Issue
Block a user