天天看點

vue+px2rem+mintUI實作H5端自适應(rem适配)

配置前言

項目建構:基于vue-cli3建構(建構時注意讓各插件可以有自己的json配置檔案),使用mintUI進行元件開發,使用px2rem-loader和postcss-px2rem-exclude進行rem适配

實作原理:每次打包,webpack通過使用插件postcss-px2rem-exclude,幫我們自動将px機關轉換成rem機關

第一步,使用vue-cli3建構基礎項目,注意建構時讓配置有各自專屬檔案,友善第六步配置postcss.config.js,具體可參考我之前寫的部落格:Vue CLI 3 使用步驟

第二步,安裝mintUI,項目根目錄下打開指令行工具,輸入:

npm install mint-ui -S
           

第三步,安裝px2rem-loader和postcss-px2rem-exclude兩個插件

npm install px2rem-loader postcss-px2rem-exclude -S
           

第四步,在根目錄src中建立util目錄下建立rem.js等比适配檔案

// rem等比适配配置檔案
// 基準大小
const baseSize = 75
// 設定 rem 函數
function setRem () {
  // 目前頁面寬度相對于 375寬的縮放比例,可根據自己需要修改,一般設計稿都是寬750(圖友善可以拿到設計圖後改過來)。
  const scale = document.documentElement.clientWidth / 375
  // 設定頁面根節點字型大小(“Math.min(scale, 2)” 指最高放大比例為2,可根據實際業務需求調整)
  document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px'
}
// 初始化
setRem()
// 改變視窗大小時重新設定 rem
window.onresize = function () {
  setRem()
}

           

第五步,在main.js中引入适配檔案

import './util/rem'
           

第六步,在根目錄postcss.config.js下配置:

module.exports = {
  plugins: {
    'autoprefixer': {},
    'postcss-px2rem-exclude': {
    //這裡注意與rem.js中的基準大小保持一緻
      'remUnit': 75,
      'exclude': '/node_modules/i'
    }
  }
}
           

示例頁面代碼,直接使用px即可,webpack編譯時會自動轉成rem

覆寫根目錄/src/App.vue

<template>
  <div id="app">
    <router-view />
  </div>
</template>

<style >
#app {
  width: 100%;
  height: 100vh;
}
* {
  margin: 0;
  padding: 0;
}
</style>
           

覆寫根目錄/src/views/Home.vue

<template>
  <div class="home">
    <div class="header">這是50px高的頭部</div>
    <div class="container">這是中間容器</div>
    <div class="footer">這是50px高的底部</div>
  </div>
</template>

<script>
export default {

}
</script>

<style  scoped>
.home {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  font-size: 20px;
  .header {
    height: 50px;
    background: yellow;
  }
  .container {
    flex: 1;
    background: cyan;
  }
  .footer {
    height: 50px;
    background: #ccc;
  }
}
</style>
           

示例頁面效果

vue+px2rem+mintUI實作H5端自适應(rem适配)

啊,interesting ٩(๑>◡<๑)۶ 。

如果文章對您有所幫助,可以将網頁收藏到浏覽器收藏夾,友善以後用到來翻,當然我就是這麼幹的。然後,點贊,關注,謝謝。