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-icon
      default-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'; // 使用默认图标
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值