mpvue框架适配Iphone X的方法_学习

最近在学习用mpvue来写小程序,记一下苹果X安全区域的适配问题

1、判断机型工具类

safe-area.js

  1. let cache = null

  2. export default function getSafeArea() {

  3. return new Promise((resolve, reject) => {

  4. if (cache != null) {

  5. // 如果有缓存不行行调用

  6. resolve(cache)

  7. } else {

  8. // 获取系统信息

  9. wx.getSystemInfo({

  10. success: ({ model, screenHeight, statusBarHeight }) => {

  11. const iphoneX = /iphone x/i.test(model)

  12. const iphoneNew = /iPhone11/i.test(model) && screenHeight === 812

  13. cache = {

  14. isIPhoneX: iphoneX || iphoneNew,

  15. statusBarHeight,

  16. }

  17. resolve(cache)

  18. },

  19. fail: reject,

  20. })

  21. }

  22. })

  23. }

2、全局组件mixin

mixins.js

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

  1. import getSafeArea from './utils/safe-area'

  2. let MyPlugin = {}

  3. MyPlugin.install = function(Vue) {

  4. // 添加全局方法或属性

  5. Vue.prototype.$isPage = function isPage() {

  6. return this.$mp && this.$mp.mpType === 'page'

  7. }

  8. // 注入组件

  9. Vue.mixin({

  10. data() {

  11. return {

  12. isIPhoneX: this.isIPhoneX,

  13. }

  14. },

  15. mounted() {

  16. if (this.$isPage()) {

  17. getSafeArea().then(({ isIPhoneX, statusBarHeight }) => {

  18. this.isIPhoneX = isIPhoneX

  19. })

  20. }

  21. },

  22. })

  23. }

  24. export default MyPlugin

在main.js中注册插件

  1. import MyPlugin from './mixins'

  2. Vue.use(MyPlugin)

3、安全距离css

  1. .btn-iphonex {

  2. padding-bottom: 34px!important;

  3. }

  4.  

  5. //吸底按钮

  6. .submit-info {

  7. width: 100%;

  8. position: fixed;

  9. bottom: 0;

  10. &.safe {

  11. bottom: 34px;

  12. }

  13. }

4、页面标签class类处理

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

  1. <i-button

  2. bind:click="submit"

  3. class="submit-info"

  4. :class="{safe:isIPhoneX}"

  5. type="primary"

  6. size="small"

  7. >确定</i-button>

 

相关文件如如下图所示

mpvue框架适配Iphone X的方法_学习_02

 

 

 

 

mpvue框架适配Iphone X的方法_学习_03