uniapp开发小程序-如何判断小程序是在手机端还是pc端打开

官方说明

https://developers.weixin.qq.com/miniprogram/dev/devtools/pc-dev.html

小程序如何判断是 PC 平台?

通过 getSystemInfo 官方接口(platform 是 windows)
通过 UA(PC UA 包含 MiniProgramEnv/Windows)

App.vue

<script>
export default {
      
      
  onLaunch: function () {
      
      
    console.warn(
      "当前组件仅支持 uni_modules 目录结构 ,请升级 HBuilderX 到 3.1.0 版本以上!"
    );
    console.log("App Launch", uni.getSystemInfoSync().platform);
    uni.setStorageSync("platform", uni.getSystemInfoSync().platform);
    uni.setStorageSync(
      "windowWidth",
      wx.getStorageSync("devices").windowWidth 
    );
    uni.setStorageSync(
      "windowHeight",
      wx.getStorageSync("devices").windowHeight 
    );
  },
  onLoad() {
      
      },
  onShow: function () {
      
      
  },
  onHide: function () {
      
      
  },
};
</script>

<style lang="scss">
/*每个页面公共css */
@import "@/uni_modules/uni-scss/index.scss";
// 设置整个项目的背景色
page {
      
      
  background-color: #f5f5f5;
}
</style>

判断是否是pc端的函数(如果宽度足够也视为pc端)

/** 是否是pc端 */
function isPC() {
    
    
  if (["windows", "mac"].some((v) => v === wx.getStorageSync("platform"))) {
    
    
    return true;
  }
  if (Number(wx.getStorageSync("windowWidth")) > 1000) {
    
    
    return true;
  }
  return false;
}

同时值得注意的是,微信开发者工具的platform属性是devtools,只能体验版中进行测试真实的platform属性

猜你喜欢

转载自blog.csdn.net/qq_42611074/article/details/134553756