0
点赞
收藏
分享

微信扫一扫

在 UniApp 中区分 H5 和微信小程序环境的多种方法

在 UniApp 中区分 H5 和微信小程序环境有多种方法,以下是全面的解决方案汇总:

📌 一、条件编译(最常用)

原理:在编译阶段根据平台过滤代码

<!-- 模板中 -->
<view>
  <!-- #ifdef H5 -->
    <view>H5 特有内容</view>
  <!-- #endif -->
  
  <!-- #ifdef MP-WEIXIN -->
    <view>微信小程序特有内容</view>
  <!-- #endif -->
</view>

// JS 逻辑中
// #ifdef H5
console.log('当前是 H5 环境');
// #endif

// #ifdef MP-WEIXIN
console.log('当前是微信小程序环境');
// #endif

📌 二、运行时环境判断

原理:通过 API 或全局变量在运行时检测环境

方法 1:使用 uni.getSystemInfoSync()

const systemInfo = uni.getSystemInfoSync();

// 判断平台
if (systemInfo.platform === 'android' || systemInfo.platform === 'ios') {
  // 移动端浏览器
} else if (systemInfo.platform === 'devtools') {
  // 开发者工具
} else if (systemInfo.platform === 'windows' || systemInfo.platform === 'mac') {
  // PC 浏览器
}

// 更精准判断
if (systemInfo.uniPlatform === 'web') {
  console.log('H5 环境');
} else if (systemInfo.uniPlatform === 'mp-weixin') {
  console.log('微信小程序');
}

方法 2:使用 process.env 环境变量

// 推荐方式
const isH5 = process.env.UNI_PLATFORM === 'h5';
const isMPWeixin = process.env.UNI_PLATFORM === 'mp-weixin';

// 或者
const isWechatMiniProgram = process.env.VUE_APP_PLATFORM === 'mp-weixin';

📌 三、自定义全局方法

原理:在 main.js 中扩展全局判断方法

// main.js
Vue.prototype.$isH5 = function() {
  return process.env.UNI_PLATFORM === 'h5';
};

Vue.prototype.$isWeapp = function() {
  return process.env.UNI_PLATFORM === 'mp-weixin';
};

// 组件中使用
if (this.$isH5()) {
  // H5 特有逻辑
}

📌 四、CSS 条件编译

原理:在样式中区分平台

/* 通用样式 */
.search-bar {
  position: fixed;
  left: 0;
  right: 0;
  z-index: 1000;
}

/* H5 特有样式 */
/* #ifdef H5 */
.search-bar {
  top: var(--window-top);
}
/* #endif */

/* 微信小程序特有样式 */
/* #ifdef MP-WEIXIN */
.search-bar {
  top: 0;
  padding-top: 44px; /* 状态栏高度 */
}
/* #endif */

📌 五、环境变量 + 计算属性

原理:结合环境变量和响应式数据

export default {
  computed: {
    platformStyle() {
      if (process.env.UNI_PLATFORM === 'h5') {
        return {
          position: 'fixed',
          top: 'var(--window-top)'
        };
      } else if (process.env.UNI_PLATFORM === 'mp-weixin') {
        return {
          position: 'fixed',
          top: `${this.statusBarHeight}px`
        };
      }
      return {};
    }
  },
  data() {
    return {
      statusBarHeight: 0
    };
  },
  mounted() {
    // #ifdef MP-WEIXIN
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight;
    // #endif
  }
}

📌 六、特殊 API 检测法

原理:通过平台特有 API 存在性判断

// 判断是否微信小程序
const isWeapp = typeof wx !== 'undefined' && 
                typeof wx.getSystemInfoSync === 'function' && 
                !window.__wxjs_environment;

// 判断是否 H5
const isH5 = typeof window !== 'undefined' && 
             typeof document !== 'undefined';

📌 七、项目配置区分

原理:在 package.jsonvue.config.js 中设置环境变量

// vue.config.js
module.exports = {
  configureWebpack: {
    plugins: [
      new webpack.DefinePlugin({
        __IS_H5__: JSON.stringify(process.env.UNI_PLATFORM === 'h5'),
        __IS_WEAPP__: JSON.stringify(process.env.UNI_PLATFORM === 'mp-weixin')
      })
    ]
  }
}

// 组件中使用
if (__IS_H5__) {
  // H5 逻辑
}

💡 最佳实践建议

  1. 优先使用条件编译

// #ifdef H5
const topPosition = 'var(--window-top)';
// #endif

// #ifdef MP-WEIXIN
const topPosition = `${statusBarHeight}px`;
// #endif

  1. 复杂场景使用组合判断

getPlatformSpecificStyle() {
  // #ifdef H5
  return { top: 'var(--window-top)' };
  // #endif
  
  // #ifdef MP-WEIXIN
  return { 
    top: `${this.statusBarHeight}px`,
    paddingRight: `${this.capsuleWidth}px`
  };
  // #endif
}

  1. 封装环境判断工具

// utils/env.js
export const isH5 = process.env.UNI_PLATFORM === 'h5';
export const isWeapp = process.env.UNI_PLATFORM === 'mp-weixin';
export const platform = process.env.UNI_PLATFORM;

// 组件中使用
import { isH5, isWeapp } from '@/utils/env';

⚠️ 注意事项

  1. 避免在非 H5 环境使用 DOM 操作

// #ifdef H5
document.querySelector('.element').style.display = 'none';
// #endif

  1. 小程序不支持 CSS 变量

/* 错误示例 */
.element {
  top: var(--window-top); /* 小程序无效 */
}

/* 正确方式 */
/* #ifdef H5 */
.element {
  top: var(--window-top);
}
/* #endif */

  1. 真机环境差异

// 永远不要依赖模拟器数据
// #ifdef MP-WEIXIN
uni.getSystemInfo({
  success: (res) => {
    // 真机才返回胶囊按钮数据
    if (res.platform !== 'devtools') {
      this.handleMenuButton(res);
    }
  }
});
// #endif

根据项目复杂度选择合适方案:

  • 简单项目:条件编译
  • 中型项目:环境变量 + 计算属性
  • 大型项目:封装环境工具类 + 配置注入
举报

相关推荐

0 条评论