// 在 app.js 中添加插件查询方法
App({
// ...
getPluginProviders() {
try {
// 获取小程序全局配置
const appConfig = wx.getAppBaseInfo && wx.getAppBaseInfo();
if (appConfig && appConfig.plugins) {
const providers = {};
Object.entries(appConfig.plugins).forEach(([name, config]) => {
providers[name] = config.provider;
});
console.log('所有插件 Provider:', providers);
return providers;
}请帮我把上述代码融入到下列代码中,然后给我完整代码const pathConfig = require('./config/path');
App({
// 全局数据对象
globalData: {
isDev: false, // 是否是开发环境
debugMode: false, // 手动调试模式标志
userInfo: null, // 用户信息
token: null, // 用户认证token
systemInfo: null, // 系统信息
apiBaseUrl: 'https://api.lyqf.com', // API基础URL
envConfig: {
develop: {
apiBaseUrl: 'https://dev-api.lyqf.com',
skipLogin: true
},
trial: {
apiBaseUrl: 'https://test-api.lyqf.com',
skipLogin: false
},
release: {
apiBaseUrl: 'https://api.lyqf.com',
skipLogin: false
}
},
tabBarPages: [ // 标签页路径列表
'/pages/home/home',
'/pages/auto-service/index',
'/pages/product-mall/index',
'/pages/finance-circle/index',
'/pages/my/index'
],
routes: { // 主要路由配置
welcome: '/pages/welcome/welcome',
login: '/pages/login/login',
phoneLogin: '/pages/phone-login/index',
home: '/pages/home/home',
autoService: '/pages/auto-service/index',
productMall: '/pages/product-mall/index',
financeCircle: '/pages/finance-circle/index',
my: '/pages/my/index',
settings: '/pages/settings/index',
profile: '/pages/profile/index'
},
pluginStatus: { // 插件状态信息
loaded: false,
version: null,
error: null
}
},
// 小程序初始化完成时触发
onLaunch(options) {
console.log('小程序初始化完成', options);
// 1. 获取系统信息
this.getSystemInfo();
// 2. 检测运行环境
this.checkEnvironment(options);
// 3. 检查插件状态
this.checkPluginStatus();
// 4. 检查登录状态
this.checkLoginStatus();
// 5. 初始化全局事件监听
this.initGlobalEvents();
// 6. 开发环境自动跳转 - 注释掉
// this.handleDevRedirect();
},
// 获取系统信息
getSystemInfo() {
try {
const systemInfo = wx.getSystemInfoSync();
this.globalData.systemInfo = systemInfo;
console.log('系统信息:', systemInfo);
} catch (e) {
console.error('获取系统信息失败:', e);
}
},
// 检测运行环境
checkEnvironment(options) {
try {
// 获取小程序版本信息
const accountInfo = wx.getAccountInfoSync();
const envVersion = accountInfo.miniProgram.envVersion || 'release';
// 设置全局环境标志
this.globalData.isDev = envVersion === 'develop';
// 应用环境配置
const envConfig = this.globalData.envConfig[envVersion] || {};
this.globalData.apiBaseUrl = envConfig.apiBaseUrl || this.globalData.apiBaseUrl;
console.log(`当前环境: ${envVersion}, API地址: ${this.globalData.apiBaseUrl}`);
// 检查URL参数中的调试标志
if (options && options.query && options.query.debug === 'true') {
this.enableDebugMode();
}
// 检查本地存储中的调试标志
const debugStorage = wx.getStorageSync('debugMode');
if (debugStorage === 'true') {
this.enableDebugMode();
}
} catch (e) {
console.error('环境检测失败:', e);
}
},
// 检查插件状态
checkPluginStatus() {
console.log('开始检查插件状态...');
// 检查插件是否已加载
try {
const plugin = requirePlugin('myPlugin');
console.log('插件加载成功:', plugin);
// 更新全局插件状态
this.globalData.pluginStatus.loaded = true;
// 检查插件版本
wx.getPluginVersion({
plugin: 'wx2d8807e6add3eaee',
success: (res) => {
console.log('插件版本信息:', res);
this.globalData.pluginStatus.version = res.version;
if (res.version !== '1.11.7') {
console.warn('插件版本不匹配:', res.version);
this.showVersionAlert(res.version);
}
},
fail: (err) => {
console.error('获取插件版本失败:', err);
this.globalData.pluginStatus.error = '获取版本失败';
this.showPluginError('获取插件版本失败');
}
});
} catch (error) {
console.error('插件加载失败:', error);
this.globalData.pluginStatus = {
loaded: false,
version: null,
error: error.message
};
this.showPluginError('插件加载失败');
}
},
// 显示插件错误弹窗
showPluginError(message) {
wx.showModal({
title: '插件错误',
content: `${message},请检查以下可能原因:
1. 小程序后台是否已添加该插件
2. 插件版本是否配置正确
3. 网络连接是否正常`,
confirmText: '前往设置',
success: (res) => {
if (res.confirm) {
this.smartNavigateTo(this.globalData.routes.settings);
}
}
});
},
// 显示版本不匹配弹窗
showVersionAlert(currentVersion) {
wx.showModal({
title: '版本不匹配',
content: `当前插件版本(${currentVersion})与配置版本(1.11.7)不一致`,
confirmText: '刷新应用',
success: (res) => {
if (res.confirm) {
wx.reLaunch({ url: '/' });
}
}
});
},
// 检查登录状态
checkLoginStatus() {
try {
const token = wx.getStorageSync('token');
const userInfo = wx.getStorageSync('userInfo');
if (token && userInfo) {
this.globalData.token = token;
this.globalData.userInfo = userInfo;
console.log('检测到已登录用户:', userInfo);
} else {
console.log('用户未登录');
}
} catch (e) {
console.error('登录状态检查失败:', e);
}
},
// 初始化全局事件监听
initGlobalEvents() {
// 监听网络状态变化
wx.onNetworkStatusChange((res) => {
console.log('网络状态变化:', res);
this.globalData.networkStatus = res;
if (!res.isConnected) {
wx.showToast({
title: '网络已断开',
icon: 'none'
});
// 网络断开时重新检查插件状态
this.checkPluginStatus();
}
});
// 监听小程序切前台
wx.onAppShow((res) => {
console.log('小程序切前台', res);
// 每次回到前台时检查token是否过期
this.checkTokenExpiration();
// 检查插件状态(防止插件被卸载)
this.checkPluginStatus();
});
// 监听小程序切后台
wx.onAppHide(() => {
console.log('小程序切后台');
});
},
// 启用调试模式
enableDebugMode() {
console.log('启用调试模式');
this.globalData.debugMode = true;
wx.setStorageSync('debugMode', 'true');
},
// 禁用调试模式
disableDebugMode() {
console.log('禁用调试模式');
this.globalData.debugMode = false;
wx.setStorageSync('debugMode', 'false');
},
// 切换调试模式
toggleDebugMode() {
const newMode = !this.globalData.debugMode;
this.globalData.debugMode = newMode;
wx.setStorageSync('debugMode', newMode.toString());
wx.showToast({
title: newMode ? '调试模式已开启' : '调试模式已关闭',
icon: 'none'
});
},
// 检查token过期
checkTokenExpiration() {
if (!this.globalData.token) return;
// 实际项目中应调用API验证token有效性
// 这里简化为检查本地存储的过期时间
const tokenExpire = wx.getStorageSync('tokenExpire');
if (tokenExpire && tokenExpire < Date.now()) {
console.log('token已过期');
this.logout();
wx.showToast({
title: '登录已过期,请重新登录',
icon: 'none'
});
}
},
// 用户登录方法
login(loginData, callback) {
wx.showLoading({
title: '登录中...',
mask: true
});
wx.request({
url: `${this.globalData.apiBaseUrl}/auth/login`,
method: 'POST',
data: loginData,
success: (res) => {
wx.hideLoading();
if (res.data.code === 0) {
// 登录成功
const token = res.data.token;
const userInfo = res.data.userInfo;
// 保存到全局数据和本地存储
this.globalData.token = token;
this.globalData.userInfo = userInfo;
wx.setStorageSync('token', token);
wx.setStorageSync('userInfo', userInfo);
// 保存token过期时间(假设有效期为7天)
const expireTime = Date.now() + 7 * 24 * 60 * 60 * 1000;
wx.setStorageSync('tokenExpire', expireTime);
console.log('登录成功', userInfo);
wx.showToast({
title: '登录成功',
icon: 'success'
});
// 执行回调
if (callback && typeof callback === 'function') {
callback(true);
}
// 登录成功后跳转到首页
this.smartNavigateTo(this.globalData.routes.home);
} else {
wx.showToast({
title: res.data.msg || '登录失败',
icon: 'none'
});
if (callback && typeof callback === 'function') {
callback(false, res.data.msg);
}
}
},
fail: (err) => {
wx.hideLoading();
wx.showToast({
title: '网络错误,请重试',
icon: 'none'
});
if (callback && typeof callback === 'function') {
callback(false, '网络错误');
}
}
});
},
// 用户登出方法
logout() {
// 清除全局数据
this.globalData.token = null;
this.globalData.userInfo = null;
// 清除本地存储
wx.removeStorageSync('token');
wx.removeStorageSync('userInfo');
wx.removeStorageSync('tokenExpire');
console.log('用户已登出');
// 跳转到登录页面
wx.reLaunch({
url: this.globalData.routes.login
});
},
// 封装的请求方法
request(options) {
// 添加token到请求头
const header = options.header || {};
if (this.globalData.token) {
header['Authorization'] = `Bearer ${this.globalData.token}`;
}
// 合并配置
const mergedOptions = {
url: `${this.globalData.apiBaseUrl}${options.url}`,
method: options.method || 'GET',
data: options.data || {},
header: header,
success: (res) => {
// 统一处理token过期
if (res.data.code === 401) {
this.logout();
wx.showToast({
title: '登录已过期,请重新登录',
icon: 'none'
});
return;
}
if (options.success) {
options.success(res);
}
},
fail: (err) => {
if (options.fail) {
options.fail(err);
} else {
wx.showToast({
title: '网络错误,请重试',
icon: 'none'
});
}
},
complete: options.complete
};
// 发送请求
wx.request(mergedOptions);
},
// 检查用户权限
checkPermission(permission) {
if (!this.globalData.userInfo || !this.globalData.userInfo.permissions) {
return false;
}
return this.globalData.userInfo.permissions.includes(permission);
},
// 增强智能路由跳转方法
smartNavigateTo(path) {
// 确保路径格式正确
if (!path.startsWith('/')) {
path = '/' + path;
}
// 检查页面是否在 tabBar 中
const isTabBarPage = this.globalData.tabBarPages.includes(path);
// 获取当前页面栈
const pages = getCurrentPages();
const currentPage = pages.length > 0 ? pages[pages.length - 1] : null;
// 计算当前页面路径
const currentPath = currentPage ? `/${currentPage.route}` : '';
// 检查是否已经在目标页面
if (currentPath === path) {
console.log('已在目标页面,不跳转');
return;
}
try {
if (isTabBarPage) {
wx.switchTab({
url: path,
success: () => console.log(`成功跳转至标签页: ${path}`),
fail: (err) => {
console.error(`标签页跳转失败: ${path}`, err);
// 备选方案:使用 reLaunch
this.fallbackNavigate(path);
}
});
} else {
wx.navigateTo({
url: path,
success: () => console.log(`成功跳转至页面: ${path}`),
fail: (err) => {
console.error(`页面跳转失败: ${path}`, err);
// 检查页面栈深度
this.fallbackNavigate(path);
}
});
}
} catch (error) {
console.error('路由跳转异常:', error);
this.fallbackNavigate(path);
}
},
// 备用跳转方法
fallbackNavigate(path) {
// 尝试使用 reLaunch 作为最终备选
wx.reLaunch({
url: path,
success: () => console.log(`reLaunch跳转成功: ${path}`),
fail: (err) => {
console.error(`reLaunch跳转失败: ${path}`, err);
this.showNavigationError();
}
});
},
// 显示导航错误提示
showNavigationError() {
wx.showModal({
title: '跳转失败',
content: '无法跳转到目标页面,请稍后重试',
showCancel: false
});
},
// 检查路由是否在 tabBar 中
isTabBarRoute(path) {
return this.globalData.tabBarPages.includes(path);
}
});
最新发布