1、项目中安装lib-flexible和postcss-plugin-px2rem
yarn add lib-flexible
yarn add postcss-plugin-px2rem --dev
2、在项目的入口main.js文件中引入lib-flexible
import lib-flexible
3、在项目的vue.config.js文件中配置postcss
module.exports = {
css: {
loaderOptions: {
postcss: {
plugins: [
require('postcss-plugin-px2rem')({
// 以设计稿1920为例, 1920 / 24 = 80
rootValue: 80,
propBlackList: ['border', 'min-width', 'max-width']
// exclude: /(node_module)/ // 如果想把前端UI框架内的px也转换成rem,请把此属性设为默认值
})
]
}
}
}
}
4、本次设计稿是1920*1080尺寸,在node_modules/lib-flexible/flexible.js中修改如下代码
// 修改之前
function refreshRem(){
var width = docEl.getBoundingClientRect().width;
if (width / dpr > 540) {
width = 540 * dpr;
}
var rem = width / 10;
docEl.style.fontSize = rem + 'px';
flexible.rem = win.rem = rem;
}
// 修改之后
function refreshRem() {
var width = docEl.getBoundingClientRect().width
// 最小1366px,最大适配2560px
if (width / dpr < 1366) {
width = 1366 * dpr
} else if (width / dpr > 2560) {
width = 2560 * dpr
}
// 设置成24等份,设计稿时1920px的,这样1rem就是80px
var rem = width / 24
docEl.style.fontSize = rem + 'px'
flexible.rem = win.rem = rem
}