Vue 图标动态加载:Ant Design Vue 的 a-tree 图标实现与优化
1. 问题描述
-
需求:在
a-tree
中根据节点数据动态显示不同的图标。 -
错误示例是使用直接引入
@/assets/img/1.jpg
作为图片路径
以下是错误代码实例
2.问题分析与解决思路
-
问题原因:
@/assets
路径在运行时无法正确解析为图片路径。 -
解决方案:通过动态导入图片资源(
import
)来解决路径问题。
3.代码实现
关键代码
import TreeIcon from '@/assets/img/1.jpg'; // 动态导入图片
完整实现代码
<template><div class="tree"><a-tree:tree-data="treeData"show-icondefault-expand-all:auto-expand-parent="true"><template #icon="{ data }"><img:src="data.thum"style="height: 12px; width: 15px; margin-right: 5px"alt=""/></template></a-tree></div>
</template><script setup>
import { ref } from "vue";
import TreeIcon from '@/assets/img/1.jpg'; // 动态导入图片const treeData = ref([{title: "parent 1",key: "0-0",thum: TreeIcon, // 使用动态导入的图片路径children: [{title: "parent 1-0",key: "0-0-0",thum: TreeIcon,children: [{ title: "leaf", key: "0-0-0-0", thum: TreeIcon },{ title: "leaf", key: "0-0-0-1", thum: TreeIcon },],},// 其他节点...],},
]);
</script>
4.优化与扩展
4-1 统一管理图片路径:将图片路径集中管理,避免重复代码。
// assets/icons.js
export const ICONS = {default: import('@/assets/img/1.jpg'),folder: import('@/assets/img/folder.png'),
};
使用时:
import { ICONS } from '@/assets/icons.js';
// ...
thum: ICONS.default,
4-2 处理图片加载失败:为图片添加错误处理逻辑,确保用户体验。
<img:src="data.thum"@error="handleImageError"style="height: 12px; width: 15px; margin-right: 5px"alt=""
/>
const handleImageError = (e) => {e.target.src = '/default-icon.png'; // 使用默认图标
};