小程序使用全局变量globalThis和代理,彻底解决getApp为空的问题
2025-01-23 08:26 阅读(72)

使用场景

看到很多人在使用getApp()时经常出现问题。

官方文档里明确:不要在定义于 App() 内的函数中,或调用 App 前调用 getApp() 。

但我们有时 不得不 在其他文件使用到,出现undefined;例如:我们公司代码里工具文件 util/util.js 就使用到getApp(),当我们在app.js引用时,就会出问题。

https://www.zuocode.com

解决方法

创建文件 utils/_app.js

let appInstance = {};

App = new Proxy(App, {
  apply() {
    let [params] = arguments[arguments.length - 1];
    const { onLaunch } = params;
    params.onLaunch = function (options) {
      appInstance = this;
      onLaunch && onLaunch.apply(this, arguments);
    };
    return Reflect.apply(...arguments);
  },
});

Object.defineProperty(globalThis, "_app", {
  get() {
    return appInstance;
  },
});

在 app.js 最顶部引用文件

import "./utils/_app.js";

在任意地方使用_app变量,无需声明,全局可用

// app.js
import "./utils/_app.js";

App({
  onLaunch() {
    console.log("app app.js =", _app);
  },
  globalData: {
    userInfo: null,
  },
});

作者:小皮虾

链接:https://juejin.cn