Files
consumer-front/src/utils/vconsole.js
T

133 lines
2.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* vConsole 调试工具管理
*
* 使用方式:
* 1. URL 参数:?vconsole=1 开启,?vconsole=0 关闭
* 2. localStorage:设置 'vconsole' 为 '1' 开启,'0' 关闭
* 3. 代码调用:import { showVConsole, hideVConsole, toggleVConsole } from '@/utils/vconsole'
*/
let vConsoleInstance = null;
// 检测是否为开发环境(兼容多种方式)
const isDev = process.env.NODE_ENV !== 'production';
/**
* 获取 vConsole 是否开启
*/
export function isVConsoleEnabled() {
if (!isDev) return false;
// 优先从 URL 参数获取(H5 环境直接读 window.location
// #ifdef H5
try {
const urlParams = new URLSearchParams(window.location.search);
const vconsoleParam = urlParams.get('vconsole');
if (vconsoleParam !== null) {
return vconsoleParam === '1' || vconsoleParam === 'true';
}
} catch (e) {
// ignore
}
// #endif
// #ifndef H5
try {
const pages = getCurrentPages();
if (pages.length > 0) {
const currentPage = pages[pages.length - 1];
const options = currentPage.$page?.options || currentPage.options || {};
if (options.vconsole !== undefined) {
return options.vconsole === '1' || options.vconsole === 'true';
}
}
} catch (e) {
// ignore
}
// #endif
// 其次从 localStorage 获取
try {
return uni.getStorageSync('vconsole') === '1';
} catch (e) {
return false;
}
}
/**
* 开启 vConsole
*/
export function showVConsole() {
if (vConsoleInstance) return;
// 动态加载 vConsole
import('vconsole').then((module) => {
const VConsole = module.default || module;
vConsoleInstance = new VConsole({
theme: 'dark',
disableLogScrolling: false,
buttonSize: 48,
});
// 增强 vConsole 按钮样式,确保不被遮挡
setTimeout(() => {
const btn = document.querySelector('#__vconsole');
if (btn) {
btn.style.zIndex = '999999';
btn.style.position = 'fixed';
btn.style.bottom = '80px';
btn.style.right = '10px';
}
}, 500);
uni.setStorageSync('vconsole', '1');
}).catch((err) => {
console.error('[vConsole] 加载失败:', err);
});
}
/**
* 关闭 vConsole
*/
export function hideVConsole() {
if (vConsoleInstance) {
vConsoleInstance.destroy();
vConsoleInstance = null;
}
try {
uni.setStorageSync('vconsole', '0');
} catch (e) {
// ignore
}
}
/**
* 切换 vConsole 状态
*/
export function toggleVConsole() {
if (vConsoleInstance) {
hideVConsole();
} else {
showVConsole();
}
}
/**
* 根据配置初始化 vConsole
*/
export function initVConsole() {
if (!isDev) return;
if (isVConsoleEnabled()) {
showVConsole();
}
}
export default {
isVConsoleEnabled,
showVConsole,
hideVConsole,
toggleVConsole,
initVConsole,
};