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: {渲染函数}}。需要充分认识这一特点,才能更好地理解上述处理方法。

相关推荐
爱勇宝6 小时前
大多数人不是在使用 AI 赚钱,而是在帮 AI 公司赚钱
前端·后端·程序员
冬奇Lab6 小时前
每日一个开源项目(第143篇):page-agent - 纯 JS 的网页 GUI Agent,无需截图、无需插件、无需后端
前端·人工智能·agent
To_OC8 小时前
LC 994 腐烂的橘子:人人都说是 BFS 入门题,我却写了三遍才过
javascript·算法·leetcode
IT_陈寒11 小时前
React的这个渲染问题连官方文档都没说清楚
前端·人工智能·后端
追逐时光者12 小时前
别再满网找零散工具了,腾讯 QQ 浏览器这个“帮小忙”工具箱真能省时间
前端·后端
如果超人不会飞12 小时前
脉络清晰的业务演进:TinyVue Timeline 时间线组件全方位实战指南
vue.js
如果超人不会飞12 小时前
从扁平到立体:掌握 TinyVue Grid 树形表格的高级实战指南
vue.js
To_OC14 小时前
LC 200 岛屿数量:经典 DFS 入门题,我第一次写居然连方向都搞错了
javascript·算法·leetcode
Asmewill14 小时前
grep&curl命令学习笔记
前端
stringwu14 小时前
Flutter 开发必备:MVI 架构的高效实现指南
前端·flutter