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、效果
自動轉換前
自動轉換后