1.介绍amfe-flexible
amfe-flexible:根据设备宽度,修改根元素html的大小,以适配不一样终端。配置可伸缩布局方案,主要是将1rem设为viewWidth/10。
2.介绍postcss-pxtorem
postcss-pxtorem:postcss的插件,用于将 px 转换成 rem

具体步骤:
1. 安装两个插件

npm install amfe-flexible --save
npm install postcss-pxtorem --save

2. 在main.js导入amfe-flexible

import 'amfe-flexible'

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

  • 在移动端适配方案中,我们通常将设计稿宽度分为 10 等份,每份对应一个 rem 值。因此 rootValue 的值应该设置为设计稿宽度除以 10,以确保将设计稿尺寸映射到正确的 rem 值。
  • 举个例子,如果设计稿宽度是375px,那么 rootValue 的计算公式为375 / 10=37.5。这意味着每个 rem 单位对应设计稿中的 37.5px。
  • 再比如,如果在样式中设置 width: 150px;,它将被转换为 width: 4rem;,因为 150px 对应设计稿中的 4rem (假设 rootValue 为 37.5)。
const pxtorem = require('postcss-pxtorem') //定义个变量引入postcss-pxtorem
module.exports = {
    css: {
     loaderOptions: {
      // 设置 scss 公用变量文件
      sass: {
        data: `@import '~@/assets/style/public.scss';`
      },
      // 按照设计稿750px 的 1/2
      postcss: {
        plugins: [
          autoprefixer(),
          pxtorem({
            rootValue: 37.5, //计算公式为:设计稿宽度 / 10。假设设计稿为375px,即rootValue设为37.5,意味着每个 rem 单位对应设计稿中的 37.5px
            propList: ['*'], //设置需要转换的属性,*为所有都进行转换
            // 该项仅在使用 Circle 组件时需要
            // 原因参见 https://github.com/youzan/vant/issues/1948
            selectorBlackList: ['van-circle__layer']
          })
        ]
      }
    }
  },
}

4. 测试结果
1)css中设置某个div宽度为375px:

.tabPicture{
  width:375px;
}

运行后发现浏览器已经转化为10rem,即375/配置的rootValue:
在这里插入图片描述
以上情况则说明postcss-pxtorem配置成功。

2)当我们在f12中切换设备时可发现:
html的字体大小跟随设备宽度进行改变,这是amfe-flexible的实现,即说明配置成功
在这里插入图片描述
在这里插入图片描述
综合以上,我们就可以以设计稿的像素大小进行开发来适配不同设备屏幕了。

Logo

前往低代码交流专区

更多推荐