uniapp + 平板 实现横竖屏样式的切换

151 阅读1分钟

方法一: 媒体查询

  • 根据需求自己设置横竖屏的宽度
<style lang='scss'>
@media only screen and (min-device-width: 375px) and (max-device-width: 812px) {
  .serve-category {
    width: 320px;

    .category-name {
      width: calc(310px / 4);
    }
  }
}

@media only screen and (min-device-width: 768px) and (max-device-width: 2000px) {
  .serve-category {
    width: 440px;

    .category-name {
      width: calc(430px / 4);
    }
  }
}
</style>

方法二: 通过 uni.onWindowResize 监听窗口尺寸变化

  • 通过写一个mixins 实现
const resizeMixin = {
  data() {
    return {
      windowResizeCallback: "",
      resizeWidth: 0, // 宽度
      resizeHeight: 0, // 高度
      isScreen: true, // 默认横屏
    };
  },
  created() {
    /* 初始化获取设备信息 */
    const systemInfo = uni.getSystemInfoSync();
    this.resizeWidth = systemInfo.windowWidth;
    this.resizeHeight = systemInfo.windowHeight;
    this.handelScreen();

    /* 监听窗口尺寸变化事件 */
    this.windowResizeCallback = (res) => {
      this.resizeWidth = res.size.windowWidth;
      this.resizeHeight = res.size.windowHeight;
      this.handelScreen();
    };
    uni.onWindowResize(this.windowResizeCallback);
  },

  methods: {
    handelScreen() {
      /* 判断横竖屏 */
      this.isScreen = this.resizeWidth > this.resizeHeight ? true : false;
    },
  },
  beforeDestroy() {
    /* 取消监听窗口尺寸变化事件 */
    uni.offWindowResize(this.windowResizeCallback);
  },
};

export default resizeMixin;

  • 使用
<script>
import resizeMixin from "@/mixin/index.js";
export default {
  mixins: [resizeMixin],
  data() {
    return {
      popupWidth: "",
    };
  },
  watch: {
    isScreen: {
      deep: true,
      immediate: true,
      handler(val) {
        this.popupWidth = val ? "716px" : "550px";
      },
    },
  },
};
</script>