Mpvue implements the configuration of apple X security zone

I. Business background

Recently, WHEN I was developing a mini program using MPvue + TS, the bottom button of iPhone X and other mobile phones was hidden. Due to the small program development, wechat dad has done a check on the model, compared with H5 processing is much more convenient. Here is a brief list of solutions.

Second, implementation ideas

  • Method of determining type
  • Injecting global componentsmixin
  • Add the global safe distance CSS
  • Page for class class processing

Third, the implementation process

1. Method of judging models

The official documentation of the applet provides a method, wx.getSystemInfo, which we can use to determine the corresponding mobile phone model of the applet, whether to add a safe distance. Create a safe-area.js file in the utility class file and write the following code, which returns a Project for easy selection.

let cache = null;
export default function getSafeArea() {
    return new Promise((resolve, reject) => {
        if(cache ! Resolve (cache); }elseWx. 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 }); }}); }Copy the code

Inject global componentsmixin

Since MPvue has the mixin property, we can use the mixin safe distance processing method. Usage is basically the same as vue. When creating mixins.js and injecting the plug-in, note that if the page type is not determined, it will also inject the method if the reference component is used. So you need to add in the judgment

  Vue.prototype.$isPage = function isPage() {
    return this.$mp && this.$mp.mpType === 'page'
  }
Copy the code

Process mounted to avoid unnecessary injection.

import getSafeArea from '.. /utils/safe-area'
let MyPlugin = {};
MyPlugin.install = function(Vue) {// Add global method or attribute Vue. Prototype.$isPage = function isPage() {
    return this.$mp && this.$mp.mpType === 'page'} // Inject the component Vue. Mixin ({data() {
      return {
        isIPhoneX: this.isIPhoneX,
      }
    },
    mounted() {
      if (this.$isPage()) { getSafeArea().then(({ isIPhoneX, statusBarHeight }) => { this.isIPhoneX = isIPhoneX }); }}})}export default MyPlugin

Copy the code

Register the plug-in in main.js

import MyPlugin from './minxins'
Vue.use(MyPlugin)
Copy the code

3. Add the global safe distance CSS

So that we don’t need to declare styles in every file, we can write safe-distance classes in the global style

.safeArea { padding-bottom: 34px! important; }Copy the code

4, the page for class class processing

Class =”{safeArea: isIPhoneX}”

    <div class="handle" :class="{safeArea: isIPhoneX}">
      <div class="home" @click="goHome"></div>
      <div class="submit" @click="buy"> Buy now </div> </div>Copy the code