From 3d3362e4300d49db23de48575d26c8d501fdbfd8 Mon Sep 17 00:00:00 2001 From: Tevin <tingquanren@163.com> Date: Fri, 20 Aug 2021 18:52:00 +0800 Subject: [PATCH] 优化跨端通讯机制,实现从全局接收App通知,并通知页面 --- bases/Pilot.js | 80 +++++++++++++++++++++++++++++++++++++-- 1 files changed, 75 insertions(+), 5 deletions(-) diff --git a/bases/Pilot.js b/bases/Pilot.js index bc09f48..d7d3966 100644 --- a/bases/Pilot.js +++ b/bases/Pilot.js @@ -3,6 +3,11 @@ * @author Tevin */ +import Taro, { getCurrentInstance } from '@tarojs/taro'; +import { Fetcher } from './Fetcher'; +import { Tools } from '@components/common/Tools'; +import project from '@project'; + export class Pilot { constructor() { @@ -16,20 +21,31 @@ const options = { methods: {}, }; - Object.getOwnPropertyNames(Object.getPrototypeOf(this)).forEach(name => { + const names = []; + // 实例本身的字段 + Object.getOwnPropertyNames(this).forEach(name => names.push(name)); + // 类的字段 + Object.getOwnPropertyNames(Object.getPrototypeOf(this)).forEach(name => names.push(name)); + // 传递 + names.forEach(name => { + // 构造器忽略,如果存在属性 $methods 也忽略 if (name === 'constructor' || name === '$methods') { return; } if (/^\$/.test(name)) { if (name === '$data' && typeof dataAdd !== 'undefined') { - // 当有传data值进来,初始值必须带data中的字段 - const dataOrig = this.$data(); + // 转换 dataAdd 中 assets 属性下的图片地址值 + if (typeof dataAdd.assets !== 'undefined') { + dataAdd.assets = Pilot.transAssets(dataAdd.assets); + } options.data = () => { + // 当有传data值进来,初始值必须带data中的字段 + const dataOrig = this.$data(); return { ...dataOrig, ...dataAdd, - } - } + }; + }; } else { options[name.replace('$', '')] = this[name]; } @@ -37,7 +53,61 @@ options.methods[name] = this[name]; } }); + this._bindTaroPage(options); return options; } + _bindTaroPage(options) { + // 非App内嵌模式,不执行 + if (!project.appHybrid) { + return; + } + // 绑定页面实例到Page + const { onLoad, onUnload, onBridge } = options; + const option2 = { + onLoad() { + const instance = getCurrentInstance(); + instance.page.$component = this; + onLoad && onLoad.call(this); + // 绑定 onBridge 到页面实例 + this.$onBridge = onBridge || (() => { + }); + }, + onUnload() { + const instance = getCurrentInstance(); + delete instance.page.$component; + onUnload && onUnload.call(this); + }, + }; + options.onLoad = option2.onLoad; + options.onUnload = option2.onUnload; + delete options.onBridge; + } + + /** + * 转换静态图片引用 + * @param assets + * @return {{}} + */ + static transAssets(assets = {}) { + const assets2 = {}; + Object.keys(assets).forEach(key => { + let asset = ''; + if (assets[key].indexOf('assets') >= 0) { + asset = assets[key].split('assets')[1]; + } else { + asset = assets[key].replace(/^[.\/\\]*/, '/'); + } + // 网页 + if (process.env.TARO_ENV === 'h5') { + assets2[key] = project.host.assetsPath + asset; + } + // 小程序 + else if (process.env.TARO_ENV === 'weapp') { + assets2[key] = Fetcher.host + project.host.assetsPath + asset; + } + }); + return assets2; + } + } \ No newline at end of file -- Gitblit v1.9.1