一、前言
一般在做移动端过程中,常用的有rem布局、px转rem工具的使用,本文将针对vue项目介绍一种px转vw布局的实现方案。
本文所用脚手架为Vue-cli搭建的,如何搭建请看作者的另一篇文章: Vue-cli3搭建Vue项目
二、正文
要想实现px转vw的自动转化,需要在项目中自少引入如下4个依赖
1、使用npm安装如下依赖
npm install postcss-import postcss-px-to-viewport postcss-url postcss-write-svg -D
2、在项目根目录下创建.postcssrc.js
该配置的官方说明文档,本文只列举最简单、且最实用的配置项
module.exports = {
"plugins": {
"autoprefixer": {},
"postcss-import": {},
"postcss-url": {},
"postcss-write-svg": {
utf8: false
},
// 官方说明文档 https://github.com/evrone/postcss-px-to-viewport/blob/HEAD/README_CN.md
"postcss-px-to-viewport": {
viewportWidth: 750, // (Number) UI设计图的宽度.
viewportHeight: 1334, // (Number)UI设计图的高度,一般可以不设置.
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) 设置要替换的最小像素值.
mediaQuery: false // (Boolean) 允许在媒体查询中转换px
}
}
}