mpvue适配iphone x

2019-12-20 21:35:26

最近在学习mpvue,记一下苹果X安全区域的适配问题

判断机型工具类

safe-area.js


let cache = null
export default function getSafeArea() {
  return new Promise((resolve, reject) => {
    if (cache != null) {
      // 如果有缓存不行行调用
      resolve(cache)
    } else {
      // 获取系统信息
      wx.getSystemInfo({
        success: ({ model, screenHeight, statusBarHeight }) => {
          const iphoneX = /iphone x/i.test(model)
          const iphoneNew = /iPhone11/i.test(model) && screenHeight === 812
          cache = {
            isIPhoneX: iphoneX || iphoneNew,
            statusBarHeight,
          }
          resolve(cache)
        },
        fail: reject,
      })
    }
  })
}

全局组件mixin

mixins.js

mounted过程中处理,避免不必要的注入


import getSafeArea from './utils/safe-area'
let MyPlugin = {}
MyPlugin.install = function(Vue) {
  // 添加全局方法或属性
  Vue.prototype.$isPage = function isPage() {
    return this.$mp && this.$mp.mpType === 'page'
  }
  // 注入组件
  Vue.mixin({
    data() {
      return {
        isIPhoneX: this.isIPhoneX,
      }
    },
    mounted() {
      if (this.$isPage()) {
        getSafeArea().then(({ isIPhoneX, statusBarHeight }) => {
          this.isIPhoneX = isIPhoneX
        })
      }
    },
  })
}
export default MyPlugin

main.js中注册插件


import MyPlugin from './mixins'
Vue.use(MyPlugin)

安全距离css

.btn-iphonex {
  padding-bottom: 34px!important;
}

//吸底按钮
.submit-info {
  width: 100%;
  position: fixed;
  bottom: 0;
  &.safe {
    bottom: 34px;
  }
}

页面标签class类处理

项目中使用了iview库的情况,按钮标签为例


<i-button
  bind:click="submit"
  class="submit-info"
  :class="{safe:isIPhoneX}"
  type="primary"
  size="small"
>确定</i-button>
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-ND 3.0 许可协议。可自由转载、引用,但需署名作者且注明文章出处。如转载至微信公众号,请在文末添加作者公众号二维码。

扫描下方二维码阅读当前文章

浏览器、微信扫码

评 论:

好文推荐
每天进步一点点~