uniapp 要求页面子组件每隔10秒请求一次接口,将实现过程记录下来。
主页面
主页面需要监听页面的显示 卸载 隐藏事件,并将事件通知给子组件。
onShow() {
var that = this;
uni.$emit('onShow', 1);
},
onUnload() {
var that = this;
uni.$emit('onUnload', 1);
},
onHide() {
var that = this;
uni.$emit('onHide', 1);
},
子组件
当子组件加载后创建定时,并监听主页面的通知,当页面隐藏或卸载时,清除定时请求。
mounted() {
var that = this;
that.getdata()
that.timer = setInterval(() => {
that.getdata()
}, 10000);
uni.$on('onShow', function(data) {
that.timer = setInterval(() => {
that.getdata()
}, 10000);
});
uni.$on('onUnload', function(data) {
clearInterval(that.timer);
that.timer = null;
});
uni.$on('onHide', function(data) {
clearInterval(that.timer);
that.timer = null;
});
},
//当组件销毁时,清除监听,避免重复监听。
destroyed() {
var that = this;
uni.$off('onShow')
uni.$off('onUnload')
uni.$off('onHide')
clearInterval(that.timer);
},
beforeDestroy() {
var that = this;
uni.$off('onShow')
uni.$off('onUnload')
uni.$off('onHide')
clearInterval(that.timer);
},