vue3.0时代来了,各个UI组件库都相继支持vue3, ant-design-vue也为了vue3提出了ant-design-vue 2.x版本,其中很很多组件也做了相应的调整,例如Icon组件。
从 2.0 开始,ant-design-vue 不再内置 Icon 组件,需使用独立的包 @ant-design/icons-vue
要使用Icon组件需要通过组件的形式引用:
import { StarOutlined, StarFilled, StarTwoTone } from '@ant-design/icons-vue';
<StarOutlined />
<StarFilled />
<StarTwoTone twoToneColor="#eb2f96" />
修改成组件形式后有个问题就出现了,如果需要动态渲染怎么办?
例如下面这个例子:
<a-menu-item v-for="item in list" :key="item.name">
<此处如何动态放置 icon>
<span>{{item.name}}</span>
</a-menu-item>
const list = [
{
icon: 'UserOutlined',
name: 'Home'
},
{
icon: 'UserOutlined',
name: 'Home'
},
]
antd给提供了一个 createFromIconfontCN
方法,方便开发者调用在 iconfont.cn 上自行管理的图标。
import { createFromIconfontCN } from '@ant-design/icons-vue';
const MyIcon = Icon.createFromIconfontCN({
scriptUrl: '//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js', // 在 iconfont.cn 上生成
});
new Vue({
el: '#app',
template: '<my-icon type="icon-example" />',
components: {
'my-icon': MyIcon,
},
});
那如果想使用antd自带的Icon,不考虑使用其他插件需要怎么办呢?
我们可以将@ant-design/icons-vue
的所有组件都引入,然后设置一个全局属性存储。
main.js:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Antd from 'ant-design-vue'
import * as antIcons from '@ant-design/icons-vue'
import 'ant-design-vue/dist/antd.css'
const app = createApp(App)
// 注册组件
Object.keys(antIcons).forEach(key => {
app.component(key, antIcons[key])
})
// 添加到全局
app.config.globalProperties.$antIcons = antIcons
app.use(Antd).use(router).use(store).mount('#app')
使用:
<template>
<a-menu-item v-for="item in list" :key="item.name">
<component :is="$antIcons[item.icon]" />
<span>{{item.name}}</span>
</a-menu-item>
</template>
这样就可以动态引用啦,如果大家还有更好的方法,欢迎留言。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。