Vue-挂载全局组件

解决修改子组件不挂载问题参考地址
具体目录结构在下方图片
在src里创建UI文件夹创建一个allTemp.js

/*
* 获取当前目录下全部的组件数组
* markRaw 让组件永久定义为不响应数据 减少不必要的性能问题
*/
import { markRaw } from 'vue'
const tempComponent: any = []
const files = import.meta.glob('./*.vue')
Object.keys(files).forEach((fileName) => {
  tempComponent.push(files[fileName])
})
/*
 *main调用的是install里面的组件
 *遍历挂载组件并导出exportInstall
 */
const allTemp: any = {
  install: async (Vue: any) => {
    for (let i = 0; i < tempComponent.length; i++) {
      let newFiles: any = null
      // vue3套了一层异步函数
      await tempComponent[i]().then((mod: any) => {
        newFiles = markRaw(mod.default)
      })
      Vue.component(newFiles.__name, newFiles)
    }
  },
}
export { allTemp, message, loading }

main.ts引入

import { createApp } from 'vue'
import './assets/main.css'
import { createPinia } from 'pinia'
import router from './router'
import App from './App.vue'
import { allTemp, message } from './components/customComponents' // 全局组件
const app: any = createApp(App)
app.use(createPinia())
app.use(router)
app.use(allTemp)
app.mount('#app')

App.vue

<template>
  <div>
    <c-icon :value="'<MenuUnfoldOutlined />'"></c-icon>
    <c-icon :value="'MenuUnfoldOutlined'"></c-icon>
    <c-icon :value="'menu-unfold-outlined'"></c-icon>
  </div>
</template>

<script setup>
</script>

c-icon 使用的是ant-design-vue ui库

<template>
  <component class="c-icons" v-if="toUpper(props?.value)" :is="resultIcon(props?.value)" />
</template>

<script lang="ts" setup>
import { defineProps, createVNode, h, ref } from 'vue'
import * as $Icon from '@ant-design/icons-vue'
const allIcon: any = $Icon
const props = defineProps({
  value: { type: String, default: '' },
  size: { type: String, default: '16px' },
})
const size = ref(props.size)
const resultIcon = (value: string) => {
  const currentIcon = createVNode(allIcon[toUpper(value)])
  return h(currentIcon)
}
// < > / - 转换 驼峰
const toUpper = (value: string) => {
  const arr = value.replace(/[\/<>]+/g, '').trim().split('-')
  for (let i = 0; i < arr.length; i++) {
    arr[i] = arr[i].replace(/^\w/, function (ele) {
      return ele.toUpperCase()
    })
  }
  return arr.join('')
}
</script>
<style lang="less" scoped>
.c-icons {
  font-size: v-bind(size);
}
</style>

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值