vue3使用Elementplus 动态显示菜单icon不生效

1.问题描述

菜单icon由后端提供,直接用的字符串返回,前端使用遍历显示,发现icon不会显示

  {'id': 8, path:'/userManagement', 'authName': "用户管理", icon: 'User', rights:['view']},

            
              
            
            {{menu.authName}}
          

import {  DataAnalysis, Promotion, DocumentCopy,Management,Files, User, Stamp} from '@element-plus/icons-vue'

2.问题出现原因

后端提供的是字符串,那么在处读取到的也是字符串,而组件中要求是一个能渲染的组件,类似如下结构:

vue3使用Elementplus 动态显示菜单icon不生效_第1张图片

3.尝试解决一

想当然的,如果后端直接返回组件形式是不是就可以了。

尝试通过shallowRef(User)形式模拟后端返回的数据,发现还是显示不出来

import { shallowRef } from 'vue'
import { User} from '@element-plus/icons-vue'

    {'id': 8, path:'/userManagement', 'authName': "用户管理", icon: shallowRef(User), rights:['view']},

数据结构如下:

vue3使用Elementplus 动态显示菜单icon不生效_第2张图片

使用也不行

4.解决——使用组件映射文件

 其实里面只是要一个组件而已,后台返回的是字符串,将字符串对应到响应的Icon组件即可。

于是写一个映射文件:将后端返回的字符串key和前端icon组件进行映射即可

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']},
]);
          
            
              
            
            {{menu.authName}}
          

...
import { iconMapping } from "@/components/mapping/menuIconMapping"

你可能感兴趣的:(Vue,前端,vue.js,vue动态icon显示)