首先自定义一个加载中组件
ccloading.vue
<template> <view class="request-loading-view" v-if="loadingShow"> <view class="loading-view"> <image class="loading-img" :src="loading" mode="aspectFit"></image> </view> </view> </template> <script setup> import loading from "@/assets/images/loading.gif" import {useCommonStore} from "@/store/common"; import {computed} from "vue"; const commonStore = useCommonStore(); const loadingShow=computed(()=> commonStore.showLoading) </script> <style scoped> .request-loading-view { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: 999999; background-color: #fff; display: flex; justify-content: center; align-items: center; } .loading-view { width: 100rpx; height: 140rpx; /* background-color: rgba(0, 0, 0, 0.6); */ border-radius: 20rpx; display: flex; justify-content: center; align-items: center; } .loading-img { width: 100%; height: 100%; } </style>
然后再pina里面保存这个 showLoading的值。判断是否显示加载中。也就是上面引入的
/store/common.ts文件
import { defineStore } from 'pinia' import piniaPersistConfig from "@/store/helper/persist";//因为persist不支持小程序的缓存。所以再这个页面重写了一下存储方式。参考这个 export interface State { showLoading: boolean; } // @ts-ignore export const useCommonStore = defineStore('pack-store', { persist: piniaPersistConfig("pack-store"), state: (): State => ({ showLoading:false,//loading是否显示 }), getters: {}, actions: { setChangeLoading(data:boolean){ console.log("changeLoading",data) this.showLoading = data; }, }, });
main.js定义全局组件。定义全局函数
import { createSSRApp } from "vue"; import Vue from "vue"; import App from "./App.vue"; import store from "./store"; import {useCommonStore} from "@/store/common"; import newRequestLoading from '@/components/ccloading/ccloading.vue'; export function createApp() { const app = createSSRApp(App); app.use(store); app.component('new-loading', newRequestLoading); const commonStore = useCommonStore(); // 添加全局属性方法 app.config.globalProperties.$loadingStatus=commonStore.showLoading; app.config.globalProperties.$loading = { show() { commonStore.setChangeLoading(true); }, hide() { commonStore.setChangeLoading(false); } } return { app, }; }
然后就可以在页面使用了
index.vue
<template> <new-loading/> </template>
<script setup lang="ts"> import {ref, reactive, getCurrentInstance} from "vue";
const instance = getCurrentInstance()?.proxy
onLoad((options) => { instance.$loading.show();//显示加载中 getHide(); })
const getHide=()=>{
instance.$loading.hide();//隐藏加载中
}