序
最近整了个移动端的项目,用的还是Vue,多少在适配上也踩了点坑,所以,就分享一下适配的操作
使用rem.ts
新建rem.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
   |  const baseSize = 32; const designDraft = 750;
  function setRem () {          const scale = document.documentElement.clientWidth / designDraft;          document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px' }
  setRem();
  window.onresize = function () {     setRem() };
 
  | 
 
在main.ts中引入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
   | import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import "./utils/rem.ts";
  Vue.config.productionTip = false
  import Vant from 'vant'; import 'vant/lib/index.css';
  Vue.use(Vant);
  new Vue({     router,     store,     render: h => h(App) }).$mount('#app')
 
   | 
 
配置postcss
下载pxtorem
在命令行运行npm install postcss-pxtorem --save
在postcss中配置pxtorem
在根目录下新建postcss.config.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
   |  module.exports = ({ file }) => {     let rootValue = 0; 	     if (file && file.dirname && file.dirname.indexOf('vant') > -1) {         rootValue = 16     } else { 		         rootValue = 32     }     return {         "plugins": {             "postcss-pxtorem": {                 "rootValue": rootValue,                 "propList": [                     "*"                 ],             }         }     } }
 
  | 
 
测试
假设项目的UI的宽是750px的,我们用下面的代码测试一下
1 2 3 4
   | <div class="home">     <div class="box"></div>     <van-button type="info">信息按钮</van-button> </div>
   | 
 
1 2 3 4 5 6 7 8 9 10
   | <style lang="scss" scoped>     .box { 		         width: 750px;         box-sizing: border-box;         border: 20px solid #42b983;         background: royalblue;         height: 200px;     } </style>
   | 
 
在iPhone6/7/8下的表现

在iPad Pro下的表现

完美运行
一些说明
如果我的设计稿是600px怎么办?
在rem.ts中把designDraft改成对应的宽度
为什么Vant的rootValue用16,其他UI库怎么办
rootValue这个配置是用来把px替换成rem用的,在这里,box的width被设置成23.4375rem
750 / 32 = 23.4375

所以为什么rootValue用16,只是单纯因为这个配置下,rem转化成的大小和px刚好是一样的
官网

我们的demo

所以其他的UI库嘛,直接看着配rootValue就完事了