最近在学习用mpvue来写小程序,记一下苹果X安全区域的适配问题
1、判断机型工具类
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,
-
})
-
}
-
})
-
}
2、全局组件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)
3、安全距离css
-
.btn-iphonex {
-
padding-bottom: 34px!important;
-
}
-
-
//吸底按钮
-
.submit-info {
-
width: 100%;
-
position: fixed;
-
bottom: 0;
-
&.safe {
-
bottom: 34px;
-
}
-
}
4、页面标签class类处理
项目中使用了iview库的情况,按钮标签为例
-
<i-button
-
bind:click="submit"
-
class="submit-info"
-
:class="{safe:isIPhoneX}"
-
type="primary"
-
size="small"
-
>确定</i-button>
相关文件如如下图所示