uniapp自定义全局loading组件(目前只适配微信小程序)

1.首先在项目根目录创建vue.config.js或者vite.config.js文件代码如下;

vue.config.js

module.exports = {
	chainWebpack: config => {
		config.module.rule('vue').use('vue-loader').loader('vue-loader').tap(options => {
			const compile = options.compiler.compile
			options.compiler.compile = (template, ...args) => {
				if(!args[0].resourcePath){
					return compile(template, ...args)
				}
				if ((args[0].resourcePath.match(/^pages/) && !args[0].resourcePath.match(/^pages\/user\/index\/index/)) || args[0].resourcePath.match(/^pageA/) || args[0].resourcePath.match(/^pagesLive/)) {
					template = template.replace(/[\s\S]+?<[\d\D]+?>/, _ => `${_}
								<new-request-loading></new-request-loading>
							`)
				}
				return compile(template, ...args)
			}
			return options
		})
	}
}

vite.config.js:

import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
import dev_url from './env/development.js';
const injectLoadingComponent = () => ({
  name: 'inject-new-request-loading',
  transform(code, id) {
    if (!id.endsWith('.vue')) return

    const isTargetPath = (
      (id.includes('/pages/') && !id.includes('/pages/user/index/index')) ||
      id.includes('/pageA/') ||
      id.includes('/pagesLive/')
    )

    if (!isTargetPath) return
    return code.replace(/<template>([\s\S]*?)<\/template>/, 
      (match, content) => `<template>
  <new-request-loading />
  ${content}
</template>`)
  }
})

export default defineConfig({
  plugins: [
    injectLoadingComponent(),
    uni() 
  ],
  server: {
    proxy: {
      '/api': {
        target: dev_url.url,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
    host: "0.0.0.0",
    port: 8080,
    https: false,
  }
});

2.main.js添加这段代码替换uniapp全局loading方法并且全局挂载组件

// #ifdef MP-WEIXIN
uni.showLoading = function(){
	store.commit("changeLoading",true)
	// 注销uniapp showLoading方法
}

uni.hideLoading = function(){
	store.commit("changeLoading",false)
}
// #endif
//请求加载组件
import newRequestLoading from './components/ccloading.vue';

//组件挂载到全局,方便每个页面使用
Vue.component('new-request-loading', newRequestLoading);

3.添加loading组件通过vuex控制组件loading状态

<template>
	<view class="request-loading-view" v-if="loading">
		<view class="loading-view">
			<image class="loading-img" src="../static/loading.gif" mode=""></image>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	export default {
		data() {
			return {};
		},
		computed: {
			...mapGetters(['loading'])
		},
	};
</script>

<style scoped>
	.request-loading-view {
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		height: 100vh;
		z-index: 999999;
		background-color: rgba(0, 0, 0, 0.001);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.loading-view {
		width: 160upx;
		height: 160upx;
		/* background-color: rgba(0, 0, 0, 0.6); */
		border-radius: 20upx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	/* 动画样式 */
	.loading {
		border: 10upx solid rgba(0, 0, 0, 0.01);
		border-radius: 50%;
		border-top: 10upx solid #666666;
		border-right: 10upx solid #666666;
		border-bottom: 10upx solid #666666;
		width: 60upx;
		height: 60upx;
		-webkit-animation: spin 1.4s linear infinite;
		animation: spin 1.4s linear infinite;
	}

	.loading-img {
		width: 60upx;
		height: 60upx;
	}

	@-webkit-keyframes spin {
		0% {
			-webkit-transform: rotate(0deg);
		}

		100% {
			-webkit-transform: rotate(360deg);
		}
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>

<think>好的,用户想在UniApp中实现toast功能,我需要先回顾一下UniApp的相关API。记得UniApp的API设计类似于微信小程序,所以可能使用uni.showToast方法。不过,用户可能不太清楚具体参数和用法,需要详细说明。 首先,要确认基本的用法,比如显示文字提示。示例代码应该包括调用uni.showToast,并传入title和duration参数。title是必填的,duration默认是1500毫秒,这些需要指出。 然后,用户可能需要不同的图标类型,比如success、loading、none。这时候需要说明icon参数的使用,并给出不同icon的示例代码。特别是none类型时,如何自定义图片,这时候image参数就派上用场了,但要注意与icon的互斥关系。 接下来,用户可能想实现更复杂的提示,比如带图标和自定义样式。这时候需要用custom参数,并且可能需要调整位置和样式。需要提醒用户注意H5端的兼容性,以及如何通过CSS修改样式。 另外,用户可能会遇到需要隐藏Toast的情况,这时候应该介绍uni.hideToast方法,并说明在什么情况下需要调用它,比如在页面跳转前隐藏提示。 还要考虑不同平台的差异,比如H5端对custom的支持情况,以及各平台默认样式的区别。需要建议用户进行测试,尤其是在目标平台上。 最后,生成相关问题时要覆盖常见的使用场景和可能遇到的问题,比如参数配置、自定义样式、多平台适配等,这样用户能进一步探索解决方案。</think>### UniApp 实现 Toast 弹窗教程 在 UniApp 中实现 Toast 弹窗可通过内置 API `uni.showToast` 实现,支持基础提示、加载状态和自定义图标等功能。以下是具体实现步骤: #### 一、基础 Toast 使用 ```javascript // 显示文字提示(默认 1500ms 后消失) uni.showToast({ title: '操作成功', duration: 2000, icon: 'none' }) ``` - `title` 为必填参数,支持字符串内容 - `duration` 控制显示时长(单位:毫秒),默认值$1500$[^1] #### 二、带状态图标 Toast ```javascript // 成功提示(带对勾图标) uni.showToast({ title: '提交成功', icon: 'success' }) // 加载状态提示 uni.showToast({ title: '加载中', icon: 'loading', duration: 3000 }) ``` 支持三种预置图标类型: 1. `success`: 成功图标(绿色对勾) 2. `loading`: 加载状态(旋转圆圈) 3. `none`: 无图标(默认值) #### 三、自定义图标 Toast ```javascript uni.showToast({ title: '自定义图标', icon: 'none', image: '/static/custom-icon.png', duration: 2500 }) ``` - `image` 参数支持本地图片路径(需注意与 `icon` 参数互斥) - 建议图片尺寸为$40px \times 40px$[^2] #### 四、高级配置 ```javascript uni.showToast({ title: '带蒙层提示', mask: true, position: 'top', success: () => { console.log('Toast 显示成功') } }) ``` - `mask`: 是否显示透明蒙层(阻止触摸操作) - `position`: 显示位置(支持`top/center/bottom`) #### 五、手动关闭 Toast ```javascript // 立即关闭已显示的 Toast uni.hideToast() ``` 需注意:页面跳转(navigateTo)前建议主动关闭 Toast #### 跨平台注意事项 1. H5 端不支持 `custom` 参数 2. 各平台默认样式存在差异,建议通过 CSS 统一样式: ```css /* 全局修改 Toast 样式 */ .uni-toast { border-radius: 8px !important; padding: 16px 24px !important; } ```
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值