1、安装依赖,终端执行
npm install postcss-pxtorem --save
npm install postcss-pxtorem@5.1.1 //安装5.1.1版本
推荐使用5.1.1版本,其他版本容易不兼容出现下图错误

2、创建utils文件夹,并创建rem.js文件
//rem.js文件
export function setRem () {
let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth
//得到html的Dom元素
let htmlDom = document.getElementsByTagName('html')[0]
//设置根元素字体大小
htmlDom.style.fontSize = htmlWidth / 10 + 'px'
}
//初始化
setRem()
// 改变窗口大小时重新设置 rem
window.addEventListener('resize', setRem, false)
3、在manin.js引入
import './utils/rem'
4、配置vue.config.js文件,如果项目没有vue.config.js文件,直接在项目根目录下创建即可
//vue.config.js文件
module.exports = { css: { loaderOptions: { postcss: { plugins: [ require("postcss-pxtorem")({ rootValue: 192, selectorBlackList: [], propList: ["*"] }) ] } } }, }
5、效果
自动转换前
自动转换后