Vue3.x+Ant+ typeScript中动态渲染icon图标
warning:
这篇文章距离上次修改已过290天,其中的内容可能已经有所变动。
在Vue 3.x + TypeScript 中使用 Ant Design Vue 动态渲染图标,你可以使用 component
和 computed
属性来实现。首先,确保你已经安装了 Ant Design Vue 并正确引入了所需的图标组件。
<template>
<a-icon :type="iconName" />
</template>
<script lang="ts">
import { defineComponent, computed } from 'vue';
import { Icon as AIcon } from '@ant-design/icons-vue';
export default defineComponent({
components: {
AIcon,
},
props: {
icon: {
type: String,
required: true,
},
},
setup(props) {
// 使用计算属性来返回图标的组件引用
const iconName = computed(() => {
// 根据传入的icon属性动态导入图标组件
return () => import(`@ant-design/icons-vue/es/icons/${props.icon}Icon`);
});
return { iconName };
},
});
</script>
在上面的代码中,我们定义了一个名为 iconName
的计算属性,它会根据传入的 icon
属性动态生成图标组件的引用。然后,在模板中我们使用 :type
绑定这个计算属性,Vue 会自动处理动态导入和渲染。
确保传入的 icon
属性值与 Ant Design Vue 中图标文件的名称相匹配,并且该图标组件已经从 @ant-design/icons-vue/es/icons
目录下正确导出。
评论已关闭