vue项目中使用postcss-pxtorem
postcss-pxtorem
npm install postcss-pxtorem --save-dev
配置文件
// https://github.com/michael-ciniawsky/postcss-load-config module.exports = { "plugins": { "postcss-import": {}, "postcss-url": {}, // to edit target browsers: use "browserslist" field in package.json "autoprefixer": { browsers: ['Android >= 4.0', 'iOS >= 7'] }, "postcss-pxtorem": { viewportWidth: 1920, // (Number) The width of the viewport. viewportHeight: 1024, // (Number) The height of the viewport. unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to. viewportUnit: 'rem', // (String) Expected units. selectorBlackList: [], // (Array) The selectors to ignore and leave as px. minPixelValue: 1, // (Number) Set the minimum pixel value to replace. mediaQuery: false, // (Boolean) Allow px to be converted in media queries. propList: ['*'] } } }
//rem (function () { let orientation = window.matchMedia("(orientation: portrait)"); let width = document.documentElement.getBoundingClientRect().width; //获取宽度 function onMatchMeidaChange(orientation) { if (orientation.matches) { // 竖屏 width = document.documentElement.getBoundingClientRect().width; //获取竖屏宽度 setTimeout(() => { // 重新计算竖屏宽度rem autoRootFontSize() }); } else { // 横屏 width = document.documentElement.getBoundingClientRect().width; //获取横屏宽度 setTimeout(() => { // 重新计算横屏宽度rem autoRootFontSize() }); } } onMatchMeidaChange(orientation); orientation.addListener(onMatchMeidaChange); /* 计算rem */ function autoRootFontSize() { //(当前屏幕宽度,最小宽度为1200)/1920*16px let setSize = Math.max(document.documentElement.getBoundingClientRect().width,1200) / 1920 * 16; //字体默认最大值为16px document.documentElement.style.fontSize = (setSize > 16 ? 16 : setSize) + 'px'; } window.addEventListener('resize', autoRootFontSize); autoRootFontSize(); })();
在App.vue引入:
import "@/assets/js/public/rem.js";
如果不想转换元素单位可以把px改为Px或者PX。
----------------------------------------------------------------------------------这里是分割线---------------------------------------------------------------------------------------------------
上面是vue-cli2+vue2的安装和配置方式
而在vue-cli3+vue3中的使用还是有区别的:
1、安装一样:
npm install postcss-pxtorem --save-dev
2、配置:
1、在根目录添加文件:postcss.config.js
module.exports = { plugins: { 'autoprefixer': { browsers: ['Android >= 4.0', 'iOS >= 7'] }, 'postcss-pxtorem': { rootValue: 16,//结果为:设计稿元素尺寸/16,比如元素宽320px,最终页面会换算成 20rem propList: ['*'] } } }
2、在src/assets/js/下添加rem.js【内容同上面的版本】,然后在App.vue中引入: import "@/assets/js/rem.js";
3、重启看是否生效即可
前端菜鸟一枚,习惯记录平时遇到的一些问题和学习笔记,觉得有用的可以点个支持!有问题的也可以加QQ814878176交流哟 : )