vue实现移动端适配(简版)

864 阅读1分钟

一、使用到的插件

(1)amfe-flexible

amfe-flexible是配置可伸缩布局方案,主要是将1rem设为viewWidth/10

(2)postcss-pxtorem

postcss-pxtorem是一款将px转换成rem格式的方式,本质上是以html标签的fontsize值为基准,动态改变元素的各种计量单位。

二、插件的安装和使用

1.安装

npm install amfe-flexible --save

npm install postcss-pxtorem --save

2.使用

(1)在main.js导入amfe-flexible

import 'amfe-flexible'

(2)配置postcss-pxtorem,可在vue.config.js、.postcssrc.js、postcss.config.js其中之一配置,权重从左到右降低,没有则新建文件,只需要设置其中一个即可:

在vue.config.js配置如下:

module.exports = {
    //...其他配置
    css: {
        loaderOptions: {
            postcss: {
                plugins: [
                    require('postcss-pxtorem')({
                        rootValue: 37.5,
                        propList: ['*']
                    })
                ]
            }
        }
    },
}

在.postcssrc.js或postcss.config.js中配置如下:

module.exports = {
    "plugins": {
        'postcss-pxtorem': {
            rootValue: 37.5,
            propList: ['*']
        }
    }
}
  • rootValue根据设计稿宽度除以10进行设置,这边假设设计稿为375,即rootValue设为37.5(根据实际情况来确定)

  • propList是设置需要转换的属性,这边*表示所有都进行转换

三、测试

(1)css中设置某类宽度为375px:

.content{
  width:375px;
}

运行后在浏览器可以发现已经转化为10rem,即375/设置的rootValue:

以上情况则说明postcss-pxtorem配置成功

(2)当我们在f12中切换设备(手机模式)时可发现:

html的字体大小跟随设备宽度进行改变,body跟随设备的dpr进行改变,这是amfe-flexible的实现,即说明配置成功。

综合以上,我们就可以以设计稿的像素大小进行开发来适配不同设备屏幕啦

  • iphone678,解决1px显示问题(index.html) <meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">