const runtimeConfig = require("../runtime-config"); // tabBar 页面由 template-compiler 按模板 navigation 写入 runtime-config.js。 const tabPages = new Set(runtimeConfig.tabPages || []); function parseQuery(query) { const result = {}; for (const pair of (query || "").split("&")) { if (!pair) continue; const [key, value = ""] = pair.split("="); result[decodeURIComponent(key)] = decodeURIComponent(value); } return result; } /** * 打开页面。目标是 tabBar 页时使用 switchTab(微信不允许 navigateTo 到 tabBar 页, * 且 switchTab 不能带参数),参数暂存到 globalData,由目标页 takePageQuery 读取。 */ function openPage(url) { const [rawPath, query = ""] = String(url).replace(/^\//, "").split("?"); const fail = (error) => console.error("openPage failed", { url, error }); if (tabPages.has(rawPath)) { getApp().globalData.pendingPageQuery = { path: rawPath, query: parseQuery(query) }; return wx.switchTab({ url: "/" + rawPath, fail }); } return wx.navigateTo({ url: "/" + rawPath + (query ? "?" + query : ""), fail }); } /** 读取并清除 openPage 为当前 tabBar 页暂存的参数;非 tabBar 页直接使用 onLoad 的 options。 */ function takePageQuery(path) { const app = getApp(); const pending = app.globalData.pendingPageQuery; if (!pending || pending.path !== String(path).replace(/^\//, "")) return {}; app.globalData.pendingPageQuery = null; return pending.query; } module.exports = { openPage, takePageQuery };