手把手教你实现VuePC端,移动端适配

一.适配方案(amfe-flexible + postcss-pxtorem)

amfe-flexible:根据屏幕宽度,自动设置html的font-size
postcss-pxtorem:自动将px单位转换成rem

二.安装插件

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

三.在vue项目中main.js中引入lib-flexible

import 'amfe-flexible';

四.配置postcss-pxtorem

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

1、在vue.config.js配置如下

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

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

module.exports = {
		    "plugins": {
		        'postcss-pxtorem': {
		            rootValue: 37.5,
		            propList: ['*']
		        }
		    }
		}

  注意点:
(1)rootValue根据设计稿宽度除以10进行设置,这边假设设计稿为375,即rootValue设为37.5;

(2)propList是设置需要转换的属性,这边*为所有都进行转换。

五.补充

如果出现报错,请降低版本后重装依赖(在package.json文件中将版本修改为如下,然后终端运行命令npm install即可)

 "dependencies": {
    "amfe-flexible": "^2.2.1",
    "postcss-pxtorem": "^5.1.1",
  },

六.测试是否配置生效

1、css中设置某类名宽度为375px:

.box{
  width: 375px;
}

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

3、 以上情况则说明postcss-pxtorem已经配置成功啦

猜你喜欢

转载自blog.csdn.net/Orange71234/article/details/131329898