Vue3.x+Ant+ typeScript动态渲染icon图标
前言
随着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
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01 -
怎样阻止微信小程序自动打开
PHP中文网 06-13