You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt3中批量复用图标组件公共逻辑的实现方案

解决方案

1. 抽离公共基础组件

在/components/icons目录下新建IconBase.vue,把所有图标重复的Props、尺寸处理逻辑和基础SVG模板都放到这里:

<script setup lang="ts">
const props = defineProps({
  size: {
    type: [Number, String],
    default: 24
  },
  color: {
    type: String,
    default: 'currentColor'
  }
})

// 统一处理尺寸单位,支持数字(自动转px)或字符串(如"2em")
const computedSize = computed(() => {
  return typeof props.size === 'number' ? `${props.size}px` : props.size
})
</script>

<template>
  <svg
    :width="computedSize"
    :height="computedSize"
    :fill="color"
    viewBox="0 0 24 24"
    xmlns="http://www.w3.org/2000/svg"
  >
    <!-- 插槽用于插入每个图标独有的SVG内容 -->
    <slot />
  </svg>
</template>

2. 改造现有图标组件

以apps.vue为例,删掉原来重复的代码,只保留当前图标独有的SVG路径,复用基础组件:

<script setup lang="ts">
import IconBase from './IconBase.vue'
</script>

<template>
  <IconBase>
    <path d="M16 13h-3V3h-2v10H8l4 4 4-4zM4 19v2h16v-2H4z" />
  </IconBase>
</template>

再比如arrow-up.vue,同样简化:

<script setup lang="ts">
import IconBase from './IconBase.vue'
</script>

<template>
  <IconBase>
    <path d="M12 8l-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14l-6-6z" />
  </IconBase>
</template>

3. 原有调用方式完全保留

你依然可以像之前一样使用这些图标组件,比如:

<IconsApps size="32" color="#ff4400" />
<IconsArrowUp />

可选优化

如果不想每个图标都手动导入IconBase,可以在Nuxt配置里开启组件自动导入,或者把IconBase注册为全局组件,但上面的基础方案已经足够轻量且满足需求。

内容的提问来源于stack exchange,提问作者none

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 08:39:56