Scenes
Different computer screen sizes are proportionally scaled and adaptive according to the width. The unit in the code still uses px, and it is restored according to the size of the design draft. It will be converted to rem automatically.
first step
install dependencies
npm install postcss-px2rem px2rem-loader --save
second step
To create a new rem.js file, you can create a new utils directory and place it under it. The rem.js code file is as follows
// rem等比适配配置文件
// 基准大小
const baseSize = 16;
// 设置 rem 函数
function setRem() {
// 当前页面屏幕分辨率相对于1920宽的缩放比例,可根据自己需要修改
let scale = document.documentElement.clientWidth / 1920;
// 下面这一行代码可以忽略,这是我另外加的,我加这行代码是为了屏幕宽度小于1280时就不继续等比缩放了
if (document.documentElement.clientWidth < 1280) scale = 1280 / 1920
// 设置页面根节点字体大小(“Math.min(scale, 2)” 指最高放大比例为2,可根据实际业务需求调整)
document.documentElement.style.fontSize = `${
baseSize * Math.min(scale, 1)}px`;
}
// 初始化
setRem();
// 改变窗口大小时重新设置 rem
window.onresize = () => {
setRem();
};
third step
Introduce rem.js in the main.js file
the fourth step
Configure the plug-in in vue.config.js, restart after configuration
// 引入等比适配插件
const px2rem = require('postcss-px2rem');
// 配置基本大小
const postcss = px2rem({
// 基准大小 baseSize,需要和rem.js中相同
remUnit: 16,
});
module.exports = {
其他代码...
css: {
loaderOptions: {
postcss: {
plugins: [
postcss,
],
},
},
}
}