前言
随着vue3成为默认版本,越来越多的开发者选择vue3进行项目的开发,UI组件库也对Vue3进行了适配,Ant Design Vue3.x升级后,icon图标的使用方式有了如下的改变:
要使用icon需要先引入后在以组件的形式使用:
import { UserOutlined, LaptopOutlined, NotificationOutlined } from '@ant-design/icons-vue';
<UserOutlined />
<LaptopOutlined />
<NotificationOutlined />
那么这样就出现了一种问题:如何动态渲染icon图标呢,特别是在我们项目中的侧边导航栏应用上。
解决办法
第一步:在main.ts中将@ant-design/icons-vue的所有组件都引入,然后设置一个全局属性存储。
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
//ant design组件 全局注册
import Antd from "ant-design-vue";
//引入CSS初始化文件
import "ant-design-vue/dist/antd.css";
const app = createApp(App);
//导入组件库
import * as antIcons from '@ant-design/icons-vue';
const icons: any = antIcons;
// 注册组件
Object.keys(icons).forEach(key => {
app.component(key, icons[key])
})
// 添加到全局
app.config.globalProperties.$antIcons = antIcons
app.use(Antd).use(store).use(router).mount("#app");
第二步:在组件中使用:
<component :is="$antIcons[item['meta']['icon']]" />
例如菜单组建当中完整页面代码
<template>
<a-layout-sider v-model:collapsed="collapsed" collapsible>
<div class="logo" />
<a-menu v-model:selectedKeys="selectedKeys" theme="dark" mode="inline">
<div v-for="(item,index) in menuList">
<a-menu-item :key="index+1" v-if="item['children'].length==0">
<component :is="$antIcons[item['meta']['icon']]" />
<span>
<router-link :to="item['path']">{{item['meta']['title']}}</router-link>
</span>
</a-menu-item>
<a-sub-menu :key="index+1" v-else>
<template #title>
<span>
<!-- <IconFont type="TableOutlined" /> -->
<component :is="$antIcons[item['meta']['icon']]" />
<span>{{item['meta']['title']}}</span>
</span>
</template>
<a-menu-item v-for="(item2,index2) in item['children']" :key="index+1+'-'+index2">
<router-link :to="item2['path']">{{item2['meta']['title']}}</router-link>
</a-menu-item>
</a-sub-menu>
</div>
</a-menu>
</a-layout-sider>
</template>
<script lang="ts">
import {
defineComponent,
} from "vue";
let menuList:any=[]
export default defineComponent({
data() {
return {
menuList,
icon:'user-outlined'
};
},
created() {
this.getRouter()
},
methods:{
getRouter(){
this.menuList=this.$router.options.routes
console.log(this.menuList)
}
}
});
</script>
<style scoped>
.ant-menu-item-selected a, .ant-menu-item-selected a:hover {
color: white;
}
.ant-menu-item a {
color: white;
}
</style>