vue3+vite+vant移动端适配记录

1、根节点rem适配

1.1、body需要设置一个默认的字体大小,可以设置为16px

<style>
    
body{
  font-size:16px;
  height:100vh;
}
#app {
  max-width: 750px;
  min-width:320px;
  overflow: hidden;
  min-height: 100vh;
  margin: 0 auto;
}

</style>

1.2、动态设置根节点rem

<template>
  <!-- <router-view /> -->
  <login></login>
</template>

<script>
import login from './page/login/index.vue'
export default {
  components:{login},
  name: "App",
  data() {
    return {

    }
  },
  setup() {
    const setRem = () => {
      const pWidth = 750;
      const pre = 100;
      const windowWidth = document.documentElement.clientWidth;
      document.documentElement.style.fontSize = (windowWidth / pWidth) * pre + 'px';
      console.log('rem适配:',windowWidth,(windowWidth / pWidth) * pre + 'px');
    }
    return {
      setRem
    }
  },
  mounted() {
    this.setRem();
    window.addEventListener("resize", this.setRem, false);
  },
  //卸载之前
  beforeUnmount() {
    window.removeEventListener("resize", this.setRem, false)
  },
};
</script>

说明:

设计稿是750px;

基点是100,即配置好后1rem=设计稿100px;

font-size:   30px=0.3rem;   

2、插件适配

2.1、安装2个插件

cnpm/ npm / yarn install postcss-pxtorem@5.1.1 --save-dev 需要指定版本,不然可能会出错!!!

cnpm/ npm / yarn install lib-flexible --save

2.2、 项目根节点添加文件:postcss.config.js

module.exports = {
  plugins: {
    'postcss-pxtorem': {
      rootValue: 52,
      // 根字体大小是 37.5
      propList: ['*'],
      selectorBlackList: ['.no__rem']
      // 过滤掉.no__rem-开头的class,不进行rem转换处理
    }
  }
}

2.3、在工具类文件中新建rem.js文件(我放在public文件夹下)

// 设置基础根文件大小
let baseSize = 52
// rem 函数
function setRem () {
  // 设计稿一般都是以375的宽度
  const scale = document.documentElement.clientWidth / 750
  // 设置页面根节点字体大小(“Math.min(scale, 2)” 指最高放大比例为2,可根据实际业务需求调整)
  document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px';
  console.log('px转rem:', baseSize * Math.min(scale, 2) + 'px')
}
// 调用方法
setRem()

// 监听窗口在变化时重新设置跟文件大小
window.onresize = function () {
  setRem()
}

2.4、main.js文件里面引入rem.js

import '../public/rem.js'

说明:

配置好后重启服务器

设计稿750px;

配置好后代码750px=设计稿的750px

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值