方案:amfe-flexible+amfe-flexible
1.amfe-flexible
amfe-flexible是配置可伸缩布局方案,主要是将1rem设为viewWidth/10。2.postcss-pxtorem
postcss-pxtorem是postcss的插件,用于将像素单元生成rem单位。
使用步骤
1、先安装amfe-flexible和postcss-pxtorem
npm install amfe-flexible --save
npm install postcss-pxtorem --save
2、在main.js中引用
import 'amfe-flexible';
3、 配置postcss-pxtorem
可在vue.config.js、.postcssrc.js、postcss.config.js其中之一配置,权重从左到右降低,没有则新建文件,只需要设置其中一个即可。
① vue.config.js(亲测该方法,可用)
module.exports = defineConfig({
"plugins":{ //新增配置
"postcss-pxtorem": {
rootValue: 37.5, // Vant 官方根字体大小是 37.5
propList: ['*'],
selectorBlackList: ['.norem'] // 过滤掉.norem-开头的class,不进行rem转换
}
}
})
②在.postcssrc.js中配置如下:
module.exports = {
plugins: {
autoprefixer: {
overrideBrowserslist: ['last 15 versions'],
browsers: ['Android >= 4.0', 'iOS >= 7', 'ie >= 10'],
},
'postcss-pxtorem': {
rootValue: 192,
propList: ['*'], //属性的选择器,*表示通用
selectorBlackList: [], //忽略的选择器
},
},
};
rootValue根据设计稿宽度除以10进行设置,这边假设设计稿为1920,即rootValue设为192;
propList是设置需要转换的属性,这边*为所有都进行转换。
测试:
css中设置某类宽度为375px:
.content{
width:375px;
}
- 运行后在浏览器可以发现已经转化为10rem,即192/设置的rootValue:
③postcss.config.js ,在根目录下新建改文件夹(亲测该方法,可用)
module.exports = {
"plugins": {
"postcss-pxtorem": {
rootValue: 37.5, // Vant 官方根字体大小是 37.5
propList: ['*'],
selectorBlackList: ['.norem'] // 过滤掉.norem-开头的class,不进行rem转换
}
}
}
根据自己的需求做了一些改造
改造需求:在同一个vue项目中,同时做pc端和移动端,但是只有css是分开写的
改造步骤:
1、在安装好的依赖文件夹node_modules中,找到amfe-flexible/index.js文件,将文件的内容复制出来
2、在src/assets/js文件中,新建amfe-flexible.js文件,粘贴步骤1的内容
3、写一个公共方法,判断是否为移动端
export function isPc() {
if (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
) {
return false
} else {
return true
}
}
4、把amfe-flexible的执行代码都放在isPc()判断下
到此就实现了,在pc端正常显示,在移动端会执行rem适配的方法。