• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Vue3.x+Ant+ typeScript动态渲染icon图标

武飞扬头像
林个名真系难
帮助1

前言
随着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>


这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgghhje
系列文章
更多 icon
同类精品
更多 icon
继续加载