开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第1天,点击查看活动详情
Vant 中的样式默认使用 px 作为单位,如果需要使用 rem 单位,推荐使用以下两个工具:
postcss-pxtorem 一款 postcss 插件,用于将 px 单位转化为 rem
lib-flexible 设置 rem 基准值
1.安装依赖
yarn add amfe-flexible
或者使用
npm i amfe-flexible
2.在 main.js 中加载执行该模块:
进行全局引入
import 'amfe-flexible'
3.安装postcss-pxtorem依赖:
yarn add -D postcss-pxtorem
或者是
npm install postcss-pxtorem -D
这里解释一下:# -D 是 --save-dev 的简写 把依赖包的版本信息写进 package.json 文件里面
4.在项目根目录中创建 postcss.config.js 文件:
主要逻辑
判断是否是vant的文件 如果是就使用 37.5为根节点字体大小, 否则使用75 因为vant使用的设计标准为37.5 但是市场现在的主流设置尺寸是750
module.exports = {
plugins: {
// postcss-pxtorem 插件的版本需要 >= 5.0.0
'postcss-pxtorem': {
rootValue({ file }) {
return file.indexOf('vant') !== -1 ? 37.5 : 75;
},
// 配置哪些文件中的尺寸需要转化为rem *表示所有的都要转化
propList: ['*'],
},
},
};
这个文件会被自执行
还有一种方法就是我们可以手动进行计算来达到适配效果
首先下载vs code插件 px2rem
之后再将其插件的默认px大小进行配置
"cssrem.rootFontSize":192.08
配置完后就可以进行计算了
计算公式:安卓 750、iphone 680. 设计稿宽 / 设备宽 * 100
mounted() {
this.calc()
// 箭头函数和普通函数function的区别: this
window.onresize = () => {
this.calc()
}
},
methods: {
calc() {
var az = 750
var vw = (az / window.outerWidth) * 100 + 'px'
document.documentElement.style.fontSize = vw
}
// rem的原理
// 1rem === html/body的font-size
// rootFontSize === 16px
// 1rem === 16px
},
总结
对移动端适配的方法就了解这么多,说的不对的,欢迎进行反驳,
今天的分享就到这里了 下期见 - 拜拜~~~