uni-app開發的頁面跳轉全局加載中
- 首先需要下載插件
- 創建加載中頁面組件
- app.vue頁面中監聽跳轉
首先需要下載插件
https://ext.dcloud.net.cn/plugin?id=20613
創建加載中頁面組件
<!-- 全局自定義加載中 -->
<template><view v-if="visible" class="global-loading"><!-- 使用CSS實現加載動畫,避免性能問題 --><xtf-loader6 style="margin-top: 30rpx;"></xtf-loader6><xtf-loader10 class="item" style="margin-top: 10rpx;"></xtf-loader10><text class="loading-text">{{ text }}</text></view>
</template><script>
export default {data() {return {visible: false,text: '加載中...'}},methods: {show(text) {this.text = text || '加載中...'this.visible = true},hide() {this.visible = false}}
}
</script><style scoped>
.global-loading {position: fixed;top: 0;left: 0;right: 0;bottom: 0;background: rgba(255, 255, 255, 1);display: flex;flex-direction: column;justify-content: center;align-items: center;z-index: 9999;
}.loading-spinner {display: flex;margin-bottom: 16px;
}.spinner-dot {width: 12px;height: 12px;margin: 0 6px;background-color: #007aff;border-radius: 100%;animation: spinner-bounce 1.4s infinite ease-in-out both;
}.spinner-dot:nth-child(1) {animation-delay: -0.32s;
}.spinner-dot:nth-child(2) {animation-delay: -0.16s;
}@keyframes spinner-bounce {0%, 80%, 100% { transform: scale(0);opacity: 0.5;} 40% { transform: scale(1);opacity: 1;}
}.loading-text {font-size: 14px;margin-top: 15px;color: #666;
}
</style>
這個就是那個插件里面的小組件,可以用在加載中進行顯示,插件下載安裝好后,就這樣直接使用代碼去調用,不用再多做別的配置。
app.vue頁面中監聽跳轉
<template><view><global-loading ref="globalLoading"></global-loading><router-view /></view>
</template>
<script>import GlobalLoading from "@/components/loading/loading.vue"export default {onLaunch: function() {console.log('App Launch')// 初始化路由攔截this.setupRouterInterceptor()},onShow: function() {console.log('App Show')},onHide: function() {console.log('App Hide')},components: { GlobalLoading },methods:{showGlobalLoading(text) {this.$refs.globalLoading.show(text)},hideGlobalLoading() {this.$refs.globalLoading.hide()},setupRouterInterceptor() {const interceptorMethods = ['navigateTo','redirectTo','reLaunch','switchTab']interceptorMethods.forEach(method => {uni.addInterceptor(method, {invoke: (args) => {this.showGlobalLoading('加載中...')return args},success: () => {// 確保頁面切換完成后再隱藏setTimeout(() => {this.hideGlobalLoading()}, 1500)},fail: (err) => {this.hideGlobalLoading()console.error('導航失敗:', err)},complete: () => {// 兜底確保loading關閉setTimeout(() => {this.hideGlobalLoading()}, 2000)}})})},}}
</script><style>/*每個頁面公共css */
</style>
這樣就可以實現頁面跳轉的時候進行加載中顯示了!!!