uniapp 定时请求接口实例组件

uniapp yekong 600℃

uniapp项目开发过程中,需要一个效果,有几个页面需要定时请求同一个接口,查询数据,如果有数据则不做反应,如果没有数据就需要弹窗提示,并根据用户操作跳转到指定页面

考虑掉这是多个页面的公共需求,所以单独抽离出来封装成为一个子组件。

子组件

子组件监听父组件信息进行接口请求触发。

<template>
	<view>
		<u-modal showCancelButton :showConfirmButton='true' @cancel="cancel" @confirm="confirm" :show="show"
			:title="title" :content='content'></u-modal>
	</view>
</template>

<script>
	import {
		GetCarInfo,
	} from '@/config/api.js'
	export default {
		components: {},
		data() {
			return {
				show: false,
				title: '',
				content: '',
				AccountId: '',
				timer: null,
			}
		},
		mounted() {
			var that = this;
			this.AccountId = JSON.parse(uni.getStorageSync('userData')).Id
			this.GetCarInfo()
			clearInterval(that.timer)
			that.timer = setInterval(() => {
				that.GetCarInfo()
			}, 5000);
			uni.$on('onShow', function(data) {
				clearInterval(that.timer)
				that.timer = setInterval(() => {
					that.GetCarInfo()
				}, 5000);
			});
			uni.$on('onHide', function(data) {
				clearInterval(that.timer)
			});
		},
		beforeDestroy() {
			uni.$off('onUnload')
			uni.$off('onHide')
			uni.$off('onShow')
		},
		methods: {
			getPop() {
				var that = this;
				that.show = true
			},
			// 取消进入首页
			cancel() {
				this.show = false
				uni.redirectTo({
					url: '/pages/home/driver/index'
				})
			},
			// 确认进入选择页面
			confirm() {
				this.show = false
				uni.redirectTo({
					url: '/packages/pages/driver/my/changeCar'
				})
			},
			GetCarInfo() {
				var that = this;
				if (!uni.getStorageSync('CarNum')) {
					return
				}
				GetCarInfo({
					params: {
						AccountId: this.AccountId
					},
					custom: {
						auth: true
					}
				}).then(res => {
					if (res.Code == 200) {
						console.log('查询接口获取车辆信息')
						if (!res.Data) {
							if (uni.getStorageSync('CarNum')) {
								uni.removeStorageSync('CarNum')
							}
							this.title = '请选择车辆'
							this.content = '车辆已被其它司机登录,请重新选择车辆'
							this.getPop()
						}
					}
				}).catch(err => {

				})
			},
		}
	}
</script>

页面监听

页面监听时间,并传递给子组件。

onShow() {
	uni.$emit('onShow', 1);
},
onUnload() {
	var that = this;
	uni.$emit('onUnload', 1);
},
onHide() {
	var that = this;
	uni.$emit('onHide', 1);
},
喜欢 (0)