1.要在項(xiàng)目中安裝 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 之前執(zhí)行
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 管理狀態(tài)
import { globalConfigStore } from "@/pinia/global";
import { storeToRefs } from "pinia";
const globalStore = globalConfigStore();
// 保持響應(yīng)式
const { getShowBlobalUpgrades } = storeToRefs(globalStore);
</script>
<style scoped>
.global-component {
width: 100vw;
height: 100vh;
position: relative; /* 使彈窗相對(duì)于父元素定位 */
}
.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; /* 彈窗相對(duì)于遮罩層定位 */
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 居中彈窗 */
background-color: white; /* 背景白色 */
color: black; /* 字體黑色 */
padding: 20px; /* 內(nèi)邊距 */
z-index: 10001; /* 確保彈窗在遮罩層上面 */
}
</style>
4. pinia 中進(jìn)行狀態(tài)管理
/**
* @description 用戶信息數(shù)據(jù)持久化
*/
import { defineStore } from 'pinia'
const globalConfigStore = defineStore('global', {
state() {
return {
// 全局控制
showBlobalUpgrades: false
}
},
actions: {
// 全局彈窗狀態(tài)切換
changeGlobalUpgrades(status) {
this.showBlobalUpgrades = status
}
},
getters: {
// 獲取全局彈窗狀態(tài)
getShowBlobalUpgrades(state) {
return state.showBlobalUpgrades
},
},
persist: {
enabled: false,
}
})
export { globalConfigStore }
5.在main.js 全局注冊(cè)
import { createSSRApp } from "vue";
// 引入
import GlobalComponent from './components/GlobalComponent/index.vue';
// 注冊(cè)掛載
app.component("GlobalComponent", GlobalComponent);
6. page.json (app.json) 中進(jìn)行插件定義,和globalStyle,或者pages同級(jí)
"insetLoader": {
"config": {
"globalDialog": "<GlobalComponent></GlobalComponent>"
},
"label": ["globalDialog"],
"package": {
"label": "view",
"options": { }
}
},
7. 在頁(yè)面中或者攔截器直接使用pinia 管理調(diào)起
// pinia方法引入
import { globalConfigStore } from "@/pinia/global";
// 獲取store
const globalStore = globalConfigStore();
// 通過(guò)Js 直接調(diào)用
globalStore.changeGlobalUpgrades(true);
示例展示,會(huì)在每個(gè)頁(yè)面中注冊(cè)這個(gè)模版,自定義通過(guò)pinia 控制 js拉起

微信截圖_20250120172610.png
主要還是通過(guò) vite-inset-loader 這個(gè)插件實(shí)現(xiàn),npm地址 訪問(wèn)查看更多