Vue功能菜单的异步加载、动态渲染

实际的Vue应用中,常常需要提供功能菜单,例如:文件下载、用户注册、数据采集、信息查询等等。每个功能菜单项,对应某个.vue组件。下面的代码,提供了一种独特的异步加载、动态渲染功能菜单的构建方法:

javascript 复制代码
<script setup>
import {defineComponent, getCurrentInstance, h} from 'vue'

//定义需要显示的功能菜单项
const menus = [
  {id: 'home', name: '首\u3000页'},
  {id: 'user.login', name: '用户登录'},
  {id: 'user.regist', name: '用户注册'},
  {id: 'college.list', name: '学院风采'},
  {id: 'query.student', name: '学生查询'},
  {id: 'enroll.chart', name: '招生一览'},
  {id: 'upload.docs', name: '资料上传'},
  {id: 'chat.room', name: '畅论空间'}
]
const app = getCurrentInstance().appContext.app                        //当前Vue应用
//异步加载.vue组件并注册
Promise.all( 
    menus.map(({id}) => id === 'home' ?
        {__name: id, setup: null, render: null} : import(`./modules/${id}.vue`))
).then(modules => modules.forEach(m => app.component(m.__name, m)))    //注册组件
const store = app.config.globalProperties.$pinia._s.get('loginer')     //状态管理数据
//动态渲染功能菜单项
const AppMenu = defineComponent({              //定义功能菜单组件
  render() {
    return h('div', {class: 'home-menu'},
                h('ul', {class: 'home-ul'},    //用无序列表构建菜单项
                    menus.map(({id, name}) =>
                        h('li', {              //无序列表的列表项,对应功能菜单项
                          id: id,              //模块id
                          innerText: name,     //菜单名
                          onClick: event => store.setModule(event.target.id) //加载模块
                }))
        ))
  }
})
</script>

<template>
  <app-menu></app-menu>
</template>

上述处理,需要细细琢磨。提示:.vue组件解析、编译后的基本构成要素为:{__name: '组件id', setup: {组合式函数}, render: {渲染函数}}。需要充分认识这一特点,才能更好地理解上述处理方法。

相关推荐
Surmon3 小时前
彻底搞懂大模型 Temperature、Top-p、Top-k 的区别!
前端·人工智能
木斯佳5 小时前
前端八股文面经大全:bilibili生态技术方向二面 (2026-03-25)·面经深度解析
前端·ai·ssd·sse·rag
不会写DN5 小时前
Gin 日志体系详解
前端·javascript·gin
冬夜戏雪6 小时前
实习面经记录(十)
java·前端·javascript
爱学习的程序媛7 小时前
【Web前端】JavaScript设计模式全解析
前端·javascript·设计模式·web
小码哥_常7 小时前
从SharedPreferences到DataStore:Android存储进化之路
前端
老黑7 小时前
开源工具 AIDA:给 AI 辅助开发加一个数据采集层,让 AI 从错误中自动学习(Glama 3A 认证)
前端·react.js·ai·nodejs·cursor·vibe coding·claude code
薛先生_0997 小时前
js学习语法第一天
开发语言·javascript·学习
jessecyj7 小时前
Spring boot整合quartz方法
java·前端·spring boot
苦瓜小生8 小时前
【前端】|【js手撕】经典高频面试题:手写实现function.call、apply、bind
java·前端·javascript