1.要在项目中安装 vite-inset-loader 插件
// pnpm
pnpm install vite-inset-loader
// npm
npm install vite-inset-loader
// yarn
yarn install vite-inset-loader
2.vite.config.js中引入该插件
import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
import viteInsetLoader from 'vite-inset-loader';
// 要保证 viteInsetLoader插件在 uni 之前执行
export default defineConfig(() => {
return {
plugins: [viteInsetLoader(), uni()],
};
})
3.在src\components下书写组件,例如GlobalComponent
<template>
<view class="global-component" v-if="getShowBlobalUpgrades">
<view class="overlay"></view>
<view class="modal">
<view> 全局弹窗 </view>
</view>
</view>
</template>
<script setup>
// src\components/GlobalComponent/index.vue
// 全局组件
defineComponent({
name: "GlobalComponent",
});
// pinia 管理状态
import { globalConfigStore } from "@/pinia/global";
import { storeToRefs } from "pinia";
const globalStore = globalConfigStore();
// 保持响应式
const { getShowBlobalUpgrades } = storeToRefs(globalStore);
</script>
<style scoped>
.global-component {
width: 100vw;
height: 100vh;
position: relative; /* 使弹窗相对于父元素定位 */
}
.overlay {
position: fixed; /* 遮罩层固定在视口 */
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色 */
z-index: 10000; /* 确保遮罩层在最上面 */
}
.modal {
position: absolute; /* 弹窗相对于遮罩层定位 */
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 居中弹窗 */
background-color: white; /* 背景白色 */
color: black; /* 字体黑色 */
padding: 20px; /* 内边距 */
z-index: 10001; /* 确保弹窗在遮罩层上面 */
}
</style>
4. pinia 中进行状态管理
/**
* @description 用户信息数据持久化
*/
import { defineStore } from 'pinia'
const globalConfigStore = defineStore('global', {
state() {
return {
// 全局控制
showBlobalUpgrades: false
}
},
actions: {
// 全局弹窗状态切换
changeGlobalUpgrades(status) {
this.showBlobalUpgrades = status
}
},
getters: {
// 获取全局弹窗状态
getShowBlobalUpgrades(state) {
return state.showBlobalUpgrades
},
},
persist: {
enabled: false,
}
})
export { globalConfigStore }
5.在main.js 全局注册
import { createSSRApp } from "vue";
// 引入
import GlobalComponent from './components/GlobalComponent/index.vue';
// 注册挂载
app.component("GlobalComponent", GlobalComponent);
6. app.json 中进行插件定义,和globalStyle,或者pages同级
"insetLoader": {
"config": {
"globalDialog": "<GlobalComponent></GlobalComponent>"
},
"label": ["globalDialog"],
"package": {
"label": "view",
"options": { }
}
},
7. 在页面中或者拦截器直接使用pinia 管理调起
// pinia方法引入
import { globalConfigStore } from "@/pinia/global";
// 获取store
const globalStore = globalConfigStore();
// 通过Js 直接调用
globalStore.changeGlobalUpgrades(true);
示例展示,会在每个页面中注册这个模版,自定义通过pinia 控制 js拉起
微信截图_20250120172610.png
主要还是通过 vite-inset-loader 这个插件实现,npm地址 访问查看更多