From e2371220e3ded67f0623ce8550cdf1570f96bff4 Mon Sep 17 00:00:00 2001 From: Tevin <tingquanren@163.com> Date: Mon, 21 Mar 2022 14:17:15 +0800 Subject: [PATCH] 实现第二版页面间通讯机制 --- bases/Pilot.js | 69 +++++++++++++++++++++++++++------- 1 files changed, 54 insertions(+), 15 deletions(-) diff --git a/bases/Pilot.js b/bases/Pilot.js index d7d3966..295eb12 100644 --- a/bases/Pilot.js +++ b/bases/Pilot.js @@ -3,7 +3,7 @@ * @author Tevin */ -import Taro, { getCurrentInstance } from '@tarojs/taro'; +import Taro, { getCurrentInstance, getCurrentPages } from '@tarojs/taro'; import { Fetcher } from './Fetcher'; import { Tools } from '@components/common/Tools'; import project from '@project'; @@ -58,32 +58,71 @@ } _bindTaroPage(options) { - // 非App内嵌模式,不执行 - if (!project.appHybrid) { - return; - } // 绑定页面实例到Page - const { onLoad, onUnload, onBridge } = options; + const { created, beforeDestroy, onMessage, onBridge } = options; const option2 = { - onLoad() { + created() { const instance = getCurrentInstance(); instance.page.$component = this; - onLoad && onLoad.call(this); - // 绑定 onBridge 到页面实例 - this.$onBridge = onBridge || (() => { - }); + // 绑定方法到页面实例 + this.$poster = Pilot.createPoster(this); + this.$onMessage = onMessage || (() => null); + this.$onBridge = onBridge || (() => null); + // 实际生命周期回调 + created && created.call(this); }, - onUnload() { + beforeDestroy() { const instance = getCurrentInstance(); delete instance.page.$component; - onUnload && onUnload.call(this); + // 实际生命周期回调 + beforeDestroy && beforeDestroy.call(this); + // 取消绑定 + this.$onMessage = null; + this.$poster = null; + this.$onBridge = null; }, }; - options.onLoad = option2.onLoad; - options.onUnload = option2.onUnload; + options.created = option2.created; + options.beforeDestroy = option2.beforeDestroy; + delete options.onMessage; + delete options.poster; delete options.onBridge; } + // 创建页面通讯器 + static createPoster($vm) { + return (pageType, action, data) => { + // 下一页 + if (pageType === 'nextPage') { + // 持续 3 秒,检测下一页是否存在 + let count = 0; + const timer = setInterval(() => { + if (++count > 60) { + clearInterval(timer); + } + const currentPages = getCurrentPages(); + const pageIndex = currentPages.findIndex(page => page.$component === $vm); + const nextPage = currentPages[pageIndex + 1]; + if (nextPage) { + clearInterval(timer); + nextPage.$component.$onMessage(action, data); + } + }, 50); + } else if (pageType === 'prevPage') { + const currentPages = getCurrentPages(); + const pageIndex = currentPages.findIndex(page => page.$component === $vm); + const prevPage = currentPages[pageIndex - 1]; + if (prevPage) { + prevPage.$component.$onMessage(action, data); + } + } else if (pageType === 'rootPage') { + const currentPages = getCurrentPages(); + const rootPage = currentPages[0]; + rootPage.$component.$onMessage(action, data); + } + }; + } + /** * 转换静态图片引用 * @param assets -- Gitblit v1.9.1