vue基于vw实现移动端自适应

背景

通过配置webpack,实现px自动转成vw,实现移动端的自适应

做法

执行以下命令安装依赖:
千万注意千万注意千万注意要指定版本,否则会报错,提示依赖需要postcss8以上版本的支持

npm i postcss-import@12.0.1 postcss-url@9.0.0 cssnano@3.10.0 postcss-aspect-ratio-mini@0.0.2 postcss-cssnext@3.1.0 postcss-px-to-viewport@0.0.3 postcss-viewport-units@0.1.6 postcss-write-svg@3.0.1 -S

接着项目根目录新增.postcssrc.js文件

module.exports = {
  "plugins": {
      "postcss-import": {},
      "postcss-url": {},
      "postcss-aspect-ratio-mini": {}, 
      "postcss-write-svg": {
          utf8: false
      },
      "postcss-cssnext": {},
      "postcss-px-to-viewport": {
          viewportWidth: 750,     // (Number) The width of the viewport.
          viewportHeight: 1334,    // (Number) The height of the viewport.
          unitPrecision: 3,       // (Number) The decimal numbers to allow the REM units to grow to.
          viewportUnit: 'vw',     // (String) Expected units.
          selectorBlackList: ['.ignore', '.hairlines'],  // (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.
      }, 
      "postcss-viewport-units":{
		  filterRule: rule => rule.selector.includes('::after') && rule.selector.includes('::before') && rule.selector.includes(':after') && rule.selector.includes(':before')
	  },
      "cssnano": {
          preset: "advanced",
          autoprefixer: false,
          "postcss-zindex": false
      }
  }
}

之后修改项目文件.browserslistrc,千万注意去掉“not dead”,否则会提示Error: Loading PostCSS Plugin failed: Unknown browser query dead

.browserslistrc

> 1%
last 2 versions

最后,运行项目,当样式写px时,则会自动转为vw,自适应配置成功。

参考

https://www.jianshu.com/p/ae0623fac11e
https://blog.csdn.net/liyunkun888/article/details/91868776
https://www.jianshu.com/p/bd9cb7861b85
https://blog.csdn.net/qq_39241544/article/details/105968832
https://zhuanlan.zhihu.com/p/164422789
https://blog.csdn.net/perryliu6/article/details/80965734

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值