步骤如下
1、先安装 amfe-flexible 和 postcss-pxtorem
postcss-pxtorem官方文档https://www.npmjs.com/package/postcss-pxtoremamfe-flexible官方文档
https://www.npmjs.com/package/amfe-flexible
npm install amfe-flexible --save
npm install postcss-pxtorem --save
2、在入口文件main.js中导入amfe-flexible
import 'amfe-flexible';
3、配置postcss-pxtorem,可在vue.config.js、.postcssrc.js、postcss.config.js其中之一配置,权重从左到右降低,没有则新建文件,只需要设置其中一个即可
在vue.config.js配置如下:
module.exports = {
//...其他配置
css: {
loaderOptions: {
postcss: {
plugins: [
require('postcss-pxtorem')({
rootValue: 37.5,
propList: ['*']
})
]
}
}
},
}
在.postcssrc.js或postcss.config.js中配置如下:
module.exports = {
"plugins": {
"autoprefixer": {},
'postcss-pxtorem': {
rootValue: 37.5, // 75表示750设计稿,37.5表示375设计稿
propList: ['*'],
selectorBlackList: ['van'],
exclude: /web/i
}
}
}
rootValue 根据设计稿宽度除以 10 进行设置,这边假设设计稿为 375,即 rootValue 设为 37.5;
propList 是设置需要转换的属性,这边 * 所有都进行转换。
4、测试结果
css中设置某类宽度为375px:
.box {
width:375px;
}
运行后在浏览器可以发现已经转化为10rem,即375/设置的rootValue: