uniapp —回调函数callBack

时间:2025-04-08 15:17:10

什么是回调函数(callBack)?

当程序跑起来时,一般情况下,应用程序(application program)会时常通过API调用库里所预先备好的函数。但是有些库函数(library function)却要求应用先传给它一个函数,好在合适的时候调用,以完成目标任务。这个被传入的、后又被调用的函数就称为回调函数。

用法案例:

            // 获取商品列表
			async getGoodsList(callBack){
				const allGoods = await this.$myRuquest({
					url:'/api/getgoods?pageindex='+ this.pageindex
				})
				this.goods = [...this.goods,...allGoods.data.message]
				// 有回调就执行,没回调就不执行
				callBack && callBack()
			},
			// 下拉刷新
			onPullDownRefresh(){
				this.pageindex = 1
				this.goods = []
				this.show = false
				setTimeout(()=>{
					this.getGoodsList(()=>{
						// 回调 getGoodsList() 的时候,加上以下这个步骤,因此需要 callBack
						uni.stopPullDownRefresh()
					})
				},1000)
		}