想移动端适配 并使用 rem吗? 您需要先看这篇文章
vue实现移动端适配步骤如下:
vue2中的适配
先安装amfe-flexible
和postcss-pxtorem
:
npm install amfe-flexible --save
npm install postcss-pxtorem --save
在main.js导入amfe-flexible
import 'amfe-flexible';
配置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是设置需要转换的属性,这边*为所有都进行转换。
测试结果:
css中设置某类宽度为375px:
.content{
width:375px;
}
运行后在浏览器可以发现已经转化为10rem,即375/设置的rootValue:
以上情况则说明postcss-pxtorem配置成功
html的字体大小跟随设备宽度进行改变,body跟随设备的dpr进行改变,这是amfe-flexible的实现,即说明配置成功。
Vue3中的适配
1. 安装 postcss-pxtorem
npm install postcss-pxtorem --save
2. 建rem.js文件
const baseSize = 37.5
// 设置 rem 函数
function setRem () {
// 当前页面宽度相对于 750 宽的缩放比例,可根据自己需要修改。
const scale = document.documentElement.clientWidth / 750
// 设置页面根节点字体大小
document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px'
}
// 初始化
setRem()
// 改变窗口大小时重新设置 rem
window.onresize = function () {
setRem()
}
3. 并引用进main.js文件内
import './rem'
4. 修改.postcssrc.js 文件
在.postcssrc.js文件内的 plugins 添加以下配置,配后就可以在开发中直接使用 px 单位开发了
module.exports = {
plugins: {
"postcss-pxtorem": {
"rootValue": 37.5,
"propList": ["*"],
},
},
};
安装过程中可能会遇到以下报错:
- 安装配置后,发现rem并没有生效,解决办法:使用vue.config.js去配置,不要用postcss.config.js
- 抛错[object Object] is not a PostCSS plugin。报错原因:
postcss-pxtorem
版本太高,更改版本为5.1.1。npm installpostcss-pxtorem@5.1.1