Vue postcss-pxtorem 将px转成rem

要将开发是编写的px转化成rem需要三步:

方法一:使用lib-flexible插件

1、安装依赖:lib-flexible、postcss-pxtorem

  yarn add postcss-pxtorem --save

  yarn add lib-flexible

2、在main.js引用lib-flexible,import ‘lib-flexible’

4、配置vue.config.js

// css配置
  css: {
    loaderOptions: {
      postcss: {
        plugins: [
          // 兼容浏览器,添加前缀
          require("autoprefixer")({
            overrideBrowserslist: [
              "Android 4.1",
              "iOS 7.1",
              "Chrome > 31",
              "ff > 31",
              "ie >= 8"
              //'last 10 versions', // 所有主流浏览器最近10版本用
            ],
            grid: true
          }),
          require("postcss-pxtorem")({
            "rootValue": 37.5,  //换算基数,可以修改,根据自己需要配置合适值
            "exclude": /(node_module|other)/, //默认false,可以(reg)利用正则表达式排除某些文件夹的方法,例如/(node_module)/ 。如果想把前端UI框架内的px也转换成rem,请把此属性设为默认值
            "propList": ["*"],
            "mediaQuery": false, //(布尔值)允许在媒体查询中转换px。
            "minPixelValue": 3 //设置要替换的最小像素值(3px会被转rem)。 默认 0        
            })
        ]
      }
    }    

最后,记得重新启动npm run serve

方法二:自定义rem.js 文件

1、依旧要安装: postcss-pxtorem

  yarn add postcss-pxtorem --save

2、在utils中新建rem.js文件

const baseSize = 32;

// 设置rem 函数
function setRem() {
  // 设计稿通常是二倍图 750,每份font-size: 32, 开发视图375,每份font-size: 16
  const scale = document.documentElement.clientWidth / 750;
  // 给根元素设置font-size
  document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px';
}

// 初始化
setRem();

window.onresize = function () {
  setRem();
}

3、在main.js中引入:import '@/utils/rem.js'

4、配置vue.config.js,如同方法一样,只需要改变 rootValue: 16 即可;

最后,记得重新启动npm run serve