移動端vue配置 REM 適配
Vant 中的樣式默認使用px作為單位,如果需要使用rem單位,推薦使用以下兩個工具:
postcss-pxtorem 是一款 postcss 插件,用於將單位轉化為 rem
amfe-flexible 用於設置 rem 基准值
一、使用 amfe-flexible 動態設置 REM 基准值(html 標簽的字體大小)
1、安裝
# yarn add amfe-flexible
npm i amfe-flexible
2、然后在 main.js 中加載執行該模塊
...
import 'amfe-flexible'
最后測試:在瀏覽器中切換不同的手機設備尺寸,觀察 html 標簽 font-size 的變化。
二、使用 postcss-pxtorem 將 px 轉為 rem
1、安裝
# yarn add -D postcss-pxtorem
# -D 是 --save-dev 的簡寫
npm install postcss-pxtorem -D
2、然后在項目根目錄中創建 postcss.config.js 文件
module.exports = { plugins: { "postcss-pxtorem": { // 設計稿 375:37.5 // 設計稿:750:75 // Vant 是基於 375 rootValue: 37.5, propList: ["*"] } } }
3、配置完畢,重新啟動服務
最后測試:在瀏覽器中審查元素的樣式查看是否已將 px 轉換為 rem。
注意:
1.只能轉換單獨的 .css|.less|.scss 之類的文件、.vue 文件中的 style 中的 px
2.不能轉換行內樣式中的 px