当前移动端比较流行的两种适配方式, 一种是将px转换为rem,另一种是将px转换为vw。
postcss-pxtorem+amfe-flexible
postcss-pxtorem 是一款 postcss 插件,用于将单位转化为 rem
amfe-flexible 用于设置 rem 基准值
安装
# yarn add amfe-flexible
npm i amfe-flexible
main.js 中加载执行该模块
import 'amfe-flexible'
使用 postcss-pxtorem 将 px 转为 rem
"plugins": {
// to edit target browsers: use "browserslist" field in package.json
"autoprefixer": {},
"postcss-pxtorem": {
rootValue: 37.5,
propList: ['*'],
selectorBlackList: [], //忽略的选择器
replace: true,
mediaQuery: false,
minPixelValue: 0
}
}
}
postcss-px-to-viewport,将px单位自动转换成viewport单位
安装
npm install postcss-px-to-viewport --save-dev
在项目根目录下面新建文件postcss.config.js,然后将以下代码加入到文件内
module.exports = {
plugins: {
autoprefixer: {},
'postcss-px-to-viewport': {
// 视窗的宽度,对应的是我们设计稿的宽度,我们公司用的是375
viewportWidth: 375,
// 视窗的高度,根据750设备的宽度来指定,一般指定1334,也可以不配置
// viewportHeight: 1334,
// 指定`px`转换为视窗单位值的小数位数
unitPrecision: 3,
// 指定需要转换成的视窗单位,建议使用vw
viewportUnit: 'vw',
// 指定不转换为视窗单位的类,可以自定义,可以无限添加,建议定义一至两个通用的类名
selectorBlackList: ['.ignore'],
// 小于或等于`1px`不转换为视窗单位,你也可以设置为你想要的值
minPixelValue: 1,
// 允许在媒体查询中转换`px`
mediaQuery: false
}
}
}
移动端调试插件 vConsole
有时候我们开发的移动端项目在PC端浏览器显示的很正常,但是到了手机上就有问题了,这可就让人很纠结,只能盲改,如何能在手机上面查看log,查看接口请求等等,你需要使用vConsole。
npm install vconsole
然后在main.js中加入以下代码:
import Vconsole from 'vconsole'
let vConsole = new Vconsole()
Vue.use(vConsole)
效果: