使用场景
看到很多人在使用getApp()时经常出现问题。
官方文档里明确:不要在定义于 App() 内的函数中,或调用 App 前调用 getApp() 。
但我们有时 不得不 在其他文件使用到,出现undefined;例如:我们公司代码里工具文件 util/util.js 就使用到getApp(),当我们在app.js引用时,就会出问题。
解决方法
-
创建文件
utils/_app.jslet 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, }, });
