Vue3移动适配

233 阅读1分钟

vite脚手架搭建项目

npm create vite@latest
或者
npm create vue@latest
(这个安装比较全面)

amfe-flexible 会根据当前页面的尺寸去设置根元素的font-size

npm i -S amfe-flexible;

postcss-pxtorem 讲px自动转换为指定单位

npm install postcss-pxtorem --save-dev

我们在main.js入口文件处进行引入

import 'amfe-flexible'

新建一个postcss.config.js文件,如有报错,可以新建文件名称为postcss.config.cjs,配置好后px自行转为rem

// postcss.config.js
module.exports = {
    plugins: {
        'postcss-pxtorem': {
            rootValue({ file }) {
                return file.indexOf('vant') !== -1?37.5:75; // vant
            },
            propList: ['*'], // 需要转换的css属性,默认*全部
        }
    }
}
//如果module.exports 报错的话;改为export default

以下是另一种方案,pc不适配,移动端适配,在html文件的head标签中加

  <script>
    const isMobile = () => {
      const flag = 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 flag ? true : false;
    }
    if (isMobile()) {
      //封装响应式像素方法,初始化单位,实现手机端1rem=100px
      const responsivePX = () => {
        //获取页面的宽度
        let deviceWidth = document.documentElement.clientWidth;
        //如果页面大于750,即px端的页面,则把html的像素锁死在100px
        if (deviceWidth > 750) deviceWidth = 750;
        document.documentElement.style.fontSize = deviceWidth / 7.5 + 'px';
      }
      // 第一次初始化像素大小
      responsivePX();
      // 监听窗口二次刷新像素大小
      window.onresize = () => {
        responsivePX();
      };
    }
  </script>