vue中PC端自适应各类屏幕(postcss-pxtorem)

1、安装postcss-pxtorem,高版本会报错

npm i [email protected] -D

2、vue.config.js里面配置postcss-pxtorem

css: {
    loaderOptions: {
      postcss: {
        plugins: [
          require('postcss-pxtorem')({
            rootValue : 16, // 浏览器默认值字体大小为16
            selectorBlackList  : [], 
            propList   : ['*'],
          }),
        ]
      }
    },
}

3、创建rem.js文件

const baseSize = 16
function setRem () {
  const scale = document.documentElement.clientWidth / 1920
  let fontSize = (baseSize * Math.min(scale, 2))>12 ? (baseSize * Math.min(scale, 2)): 12
  document.documentElement.style.fontSize = fontSize + 'px'
}
setRem()
window.onresize = function () {
  setRem()
}

4、在main.js内引入

import '@/util/rem'

5、如果项目部署在线上后不生效,我的办法是在根目录创建postcss.config.js,将第二步vue.config.js里面的配置放在postcss.config.js中

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

6、重启+执行

猜你喜欢

转载自blog.csdn.net/weixin_57246783/article/details/127364880