Vant 中的样式默认使用 px
作为单位,如果需要使用 rem
单位,推荐使用以下两个工具:
-
lib-flexible 用于设置 rem 基准值
-
postcss-pxtorem 是一款 postcss 插件,用于将单位转化为 rem
下面我们分别将这两个工具配置到项目中完成 REM 适配。
一、使用 lib-flexible 动态设置 REM 基准值(html 标签的字体大小 )
1、安装
# yarn add amfe-flexible
npm i amfe-flexible
2、然后在 main.js
中加载执行该模块
import 'amfe-flexible'
3.最后测试:在浏览器中切换不同的手机设备尺寸,观察 html 标签 font-size
的变化。
二、使用 postcss-pxtorem 将 px
转为 rem
1、安装
# yarn add postcss-pxtorem@5.1.1 -D
# -D 是 --save-dev 的简写
npm install postcss-pxtorem@5.1.1 -D // 建议这个版本号
2、然后在项目根目录中创建 .postcssrc.js
或 postcss.config.js
文件
vant中有描述 关于适配的使用 Vant 3 - Lightweight Mobile UI Components built on Vue
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 37.5, // 如果将来是自己的设计图(750px),直接写75即可! 就可以设计图是多少px,css书写就写多少px
propList: ['*'],
},
},
};
但是上述配置只适用于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
,例如<div style="width: 200px;"></div>