1.问题描述
菜单icon由后端提供,直接用的字符串返回,前端使用遍历显示,发现icon不会显示
{'id': 8, path:'/userManagement', 'authName': "用户管理", icon: 'User', rights:['view']},
<el-menu-item :index="menu.path" v-for="menu in menuList" :key="menu.id">
<el-icon v-if="menu.icon">
<component :is="menu.icon"/>
</el-icon>
{{menu.authName}}
</el-menu-item>
import { DataAnalysis, Promotion, DocumentCopy,Management,Files, User, Stamp} from '@element-plus/icons-vue'
2.问题出现原因
后端提供的是字符串,那么在<component :is="menu.icon"/>处读取到的也是字符串,而<component>组件中要求是一个能渲染的组件,类似如下结构:
3.尝试解决一
想当然的,如果后端直接返回组件形式是不是就可以了。
尝试通过shallowRef(User)形式模拟后端返回的数据,发现还是显示不出来
import { shallowRef } from 'vue'
import { User} from '@element-plus/icons-vue'
{'id': 8, path:'/userManagement', 'authName': "用户管理", icon: shallowRef(User), rights:['view']},
数据结构如下:
使用<component :is="menu.icon._value"/>也不行
4.解决——使用组件映射文件
其实<component>里面只是要一个组件而已,后台返回的是字符串,将字符串对应到响应的Icon组件即可。文章来源:https://www.toymoban.com/news/detail-672520.html
于是写一个映射文件:将后端返回的字符串key和前端icon组件进行映射即可文章来源地址https://www.toymoban.com/news/detail-672520.html
import { DataAnalysis, Promotion, DocumentCopy,Management,Files, User, Stamp} from '@element-plus/icons-vue'
export const iconMapping = {
"dataAnalysis": DataAnalysis,
"promotion": Promotion,
"documentCopy": DocumentCopy,
"management": Management,
"files": Files,
"user": User,
"stamp": Stamp,
}
const menuList = Object.freeze([
{'id': 1, path:'/uploadSpec','authName': "上传spec", icon: 'dataAnalysis', children:[], rights:['view','add','edit','delete']},
{'id': 2, path:'/showSpec', 'authName': "Spec预览", icon: 'dataAnalysis',children:[], rights:['view','add','edit','delete']},
{'id': 3, path:'/generateTxt', 'authName': "生成测试数据", icon: 'dataAnalysis',children:[], rights:['view','add','edit','delete']},
{'id': 4, path:'/generateCronjob', 'authName': "生成转码程序", icon: 'promotion',children:[], rights:['view','add','edit','delete']},
{'id': 5, path:'/pdfCompare', 'authName': "PDF文档对比", icon: 'documentCopy',children:[], rights:['view','add','edit','delete']},
{'id': 6, path:'/resourceUpdate', 'authName': "资源更新管理", icon: 'management',children:[], rights:['view','add','edit','delete']},
{'id': 7, path:'/generateTestCase', 'authName': "自动生成ST/SIT案例", icon: 'files',children:[], rights:['view','add','edit','delete']},
{'id': 8, path:'/userManagement', 'authName': "用户管理", icon:'user', rights:['view']},
{'id': 9, path:'/roleManagement', 'authName': "角色管理", icon: 'stamp', rights:['view']},
]);
<el-menu-item :index="menu.path" v-for="menu in menuList" :key="menu.id">
<el-icon v-if="menu.icon">
<component :is="iconMapping[menu.icon]"/>
</el-icon>
{{menu.authName}}
</el-menu-item>
...
import { iconMapping } from "@/components/mapping/menuIconMapping"
到了这里,关于vue3使用Elementplus 动态显示菜单icon不生效的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!