Vant 中的樣式默認使用 px 作為單位,如果需要使用 rem 單位,推薦使用以下兩個工具:
lib-flexible (opens new window)用於設置 rem 基准值
postcss-pxtorem (opens new window)是一款 postcss 插件,用於將單位轉化為 rem
下面我們分別將這兩個工具配置到項目中完成 REM 適配。
一、使用 lib-flexible (opens new window)動態設置 REM 基准值(html 標簽的字體大小)
1、安裝
# yarn add amfe-flexible
npm i amfe-flexible
2、然后在 main.js 中加載執行該模塊
import 'amfe-flexible'
3、最后測試:在瀏覽器中切換不同的手機設備尺寸,觀察 html 標簽 font-size 的變化


二、使用 postcss-pxtorem (opens new window)將 px 轉為 rem
1、安裝
# yarn add -D postcss-pxtorem
# -D 是 --save-dev 的簡寫
npm install postcss-pxtorem@5.1.1 -D // **建議這個版本號**
2、然后在項目根目錄中創建 .postcssrc.js 文件
vant中有描述 關於適配的使用 https://vant-contrib.gitee.io/vant/#/zh-CN/advanced-usage#rem-bu-ju-gua-pei
module.exports = {
plugins: {
//自動添加瀏覽器廠商聲明前綴,用來兼容不同的瀏覽器
//VueCLI已經在內部默認配置了autoprefixer
//autoprefixer: {
// //browsers用來配置要兼容到的系統(瀏覽器)環境l/l/
// 這個配置沒有問題,但是寫到這里會有控制台編譯警告
//為什么?因為 VueCLI是通過項目中的 .browserslistrc 文件來配置要兼容的環境信息的,所有要修改.browserslistrc
/ / browsers: [ ' Android >= 4.0', 'i0S >= 8 ']
/ / },
'postcss-pxtorem': {
rootValue: 37.5, // 如果將來是自己的設計圖(750px),直接寫75即可! 就可以設計圖是多少px,css書寫就寫多少px
propList: ['*'],
},
},
};
修改.browserslistrc

但是上述配置只適用於vant內部的相關組件內容,我們自己書寫的樣式,並不是按照這個,我們希望設計圖是多少px,就寫多少px,故而修改內容如下
module.exports = {
plugins: {
// postcss-pxtorem 插件的版本需要 >= 5.0.0
'postcss-pxtorem': {
rootValue({ file }) { // 如果是vant的就按照375 尺寸, 如果是其他的就是按照750
return file.indexOf('vant') !== -1 ? 37.5 : 75; // rootValue 的值一般是 設計稿 1/10
},
propList: ['*'],
},
},
};
3、配置完畢,重新啟動服務
最后測試:刷新瀏覽器頁面,審查元素的樣式查看是否已將 px 轉換為 rem。


需要注意的是:
該插件不能轉換行內樣式中的 px,例如
