安装:
npm install postcss-pxtorem -D
vue.config.js
文件设置:
css: {
loaderOptions: {
scss: {
additionalData: `@import "~element-ui/packages/theme-chalk/src/common/var.scss";@import"@/styles/variables.scss";`
},
postcss: {
postcssOptions: {
plugins: [
require("postcss-pxtorem")({
// 配置文档:https://www.npmjs.com/package/postcss-pxtorem
rootValue: 16, // 根元素字体大小 16/1.25
unitPrecision: 5, // 转换成rem后保留的小数点位数
propList: ["*"], // 匹配CSS中的属性,* 代表启用所有属性
// exclude: /(node_module)/, // 忽略一些文件,不进行转换,默认false,可以(reg)利用正则表达式排除某些文件夹的 方法,例如/(node_module)/ 。如果想把前端UI框架内的px也转换成rem,请把此属性设为默认值
mediaQuery: false, //(布尔值)允许在媒体查询中转换px
minPixelValue: 1, // 设置要替换的最小像素值
}),
],
},
},
}
},
创建一个js文件,引入main.js
文件
// 基准大小
const baseSize = 16;
// 设置 rem 函数
function setRem() {
// 当前页面宽度相对于 1920 宽的缩放比例,可根据自己需要修改。
const scale = document.documentElement.clientWidth / 1920;
// 设置页面根节点字体大小,设置个最小值,避免字体太小
let fontSize = Math.max(baseSize * Math.min(scale, 2) ,12)
document.documentElement.style.fontSize = fontSize+"px";
}
// 初始化
setRem();
// 改变窗口大小时重新设置 rem
window.onresize = function () {
setRem();
};
在实际开发中,echarts
组件也需要根据实际进行字体转换,在utils.js
文件中创建方法
export function fontSize(res) {
let clientWidth =
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
if (!clientWidth) return;
// 此处的1920 为设计稿的宽度,记得修改!
let fontSize = clientWidth / 1920;
return res * fontSize;
}
使用,例如:
import {fontSize} from "@/utils/index.js"
legend: {
itemWidth: 6,
itemGap: 20,
x: "left",
y: "top",
textStyle: {
fontSize: fontSize(14),
color: "#666666",
},
},