Vue中rem与postcss-pxtorem的应用详解

rem 布局

rem是根元素(html)中的font-size值。

rem布局不多赘述,有很多详细说明rem布局原理的资料。

简单的说,通过JS获取设备宽度动态设定rem值,以实现在不同宽度的页面中使用rem作为单位的元素自适应的效果。

新建rem.js文件,于main.js中引用

// 设计稿以1920px为宽度,而我把页面宽度设计为10rem的情况下

const baseSize = 192; // 这个是设计稿中1rem的大小。
function setRem() {
  // 实际设备页面宽度和设计稿的比值
  const scale = document.documentElement.clientWidth / 1920;
  // 计算实际的rem值并赋予给html的font-size
  document.documentElement.style.fontSize = (baseSize * scale) + 'px';
}
setRem();
window.addEventListener('resize', () => {
  setRem();
});

postcss-pxtorem

postcss-pxtorem是PostCSS的插件,用于将像素单元生成rem单位。

安装

新建Vue项目
安装 postcss-pxtorem

npm install postcss-pxtorem --save-dev

配置

可以通过3个地方来添加配置,配置文件皆位于vue 项目根目录中,若文件不存在可以自行建立。

其中最重要的是这个:

rootValue (Number)

  • 根元素的值,即1rem的值
  • 用于设计稿元素尺寸/rootValue
  • 比如 rootValue = 192 时,在css中width: 960px; 最终会换算成width: 5rem;

还有一些其他的配置:

propList (Array) 需要做单位转化的属性.

  • 必须精确匹配
  • 用 * 来选择所有属性. Example: ['*']
  • 在句首和句尾使用 * (['*position*'] 会匹配 background-position-y)
  • 使用 ! 来配置不匹配的属性. Example: ['*', '!letter-spacing']
  • 组合使用. Example: ['*', '!font*']

minPixelValue(Number) 可以被替换的最小像素.

unitPrecision(Number) rem单位的小数位数上限.

完整的可以看官方文档

权重

vue.config.js > .postcssrx.js > postcss.config.js

其中 postcssrc.js 和 postcss.config.js 可以热更新, vue.config.js 中做的修改要重启devServer

配置示例

vue.config.js

module.exports = {
  //...其他配置
  css: {
   loaderOptions: {
    postcss: {
     plugins: [
      require('postcss-pxtorem')({
       rootValue: 192,
       minPixelValue: 2,
       propList: ['*'],
      })
     ]
    }
   }
  },
 }

.postcssrx.js

module.exports = {
  plugins: {
    'postcss-pxtorem': {
      rootValue: 16,
      minPixelValue: 2,
      propList: ['*'],
    }
  }
}

postcss.config.js

module.exports = {
 plugins: {
  'postcss-pxtorem': {
   rootValue: 192,
   minPixelValue: 2,
   propList: ['*'],
  }
 }
}

Reference

官方Github仓库:postcss-pxtorem
vue3.0中使用postcss-pxtorem
关于vue利用postcss-pxtorem进行移动端适配的问题

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持来客网。