uniapp 小程序注册全局弹窗组件(无需引入,无需写标签)

发布于:2024-07-14 ⋅ 阅读:(163) ⋅ 点赞:(0)

由于uniapp没有开放根节点,所以一般情况下通过app.components注册,在需要的页面直接写组件标签,但是如果每个页面都需要的话,再每个都加的话会非常的麻烦

网上的思路都不咋地:

1.通过写一个透明弹窗页面来实现,亲测页面透明设置无效。

2.通过编写全局组件每个页面都引入,非常不方便。


这里采用vite插件实现,这里满足uniapp+Vue3+vite 目前小程序测试没有问题

安装插件

npm i @yck-web/vite-plugin-template-inset 

 配置:

//修改配置vite.config.js, plugins中添加插件(位置需要放在uni()方法前面)
import uni from "@dcloudio/vite-plugin-uni";
  import vitePluginTemplateInset from "@yck-web/vite-plugin-template-inset";

  plugins: [
     vitePluginTemplateInset(['<GlobalDialog ref=\'GlobalDialog\'></GlobalDialog>']),
     uni(),
  ],
//main.js全局注册

import GlobalDialog from '@/components/GlobalDialog'

app.component('GlobalDialog', GlobalDialog)
<!-- 弹窗口组件 -->
<template name="globalDialog">
  <view class="mask position-fixed bg-#000 opacity-60% w-100vh h-100vh" style="z-index:1" v-if="show">
		mask
  </view>
</template>


<script setup lang="ts">
import { ref } from "vue";

let show = ref(false);

const open = () => {
  show.value = true;
};
const close = () => {
  show.value = false;
};


//暴露open和close方法
defineExpose({
  open,
  close,
});
</script>
<style lang="scss" scoped>

</style>
//页面使用
const instance = getCurrentInstance()
const showGlobalPop = () => {
		instance?.refs?.GlobalDialog?.open();
	}

网站公告

今日签到

点亮在社区的每一天
去签到