vue 3.x移动端适配

2023-09-12  本文已影响0人  天上飞的狒狒
vue3中用 amfe-flexible + postcss-pxtorem

amfe-flexible:根据屏幕宽度,自动设置html的font-size
postcss-pxtorem:自动将px单位转换成rem

  <style>
 /*消除很多标签自带的padding和marging */
    * {
      margin: 0;
      padding: 0;
    }
/*设置背景颜色*/
 body {
      background-color: #f4fdff;
    }
    /*设置最大宽度 */
    @media screen and (min-width: 500px) { 
      html {
        font-size: 50px !important;
      }
    }
    /*设置最小宽度 */
    @media screen and (max-width: 320px) {
      html {
        font-size: 32px !important;
      }
    }
  </style>
#app {
  margin: 0 auto;   /* 居中显示 */
  max-width: 420px;   /* 设置最大宽度显示 */
}
 <!-- width: 设置布局视口的宽度  device-width是获取用户设备的宽度 -->
  <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1, minimum-scale=1,user-scalable=no">
1.引入amfe-flexible
npm i -S amfe-flexible
2. 引入 postcss-pxtorem
npm install postcss-pxtorem --save-dev
3. 安装完后我们先在main.js中引入amfe-flexible
import 'amfe-flexible'
4 接着在项目"根目录"新建一个postcss.config.js文件

5. 或者可在vue.config.js、.postcssrc.js、postcss.config.js其中之一配置,权重从左到右降低,没有则新建文件,只需要设置其中一个即可

1、在vue.config.js配置如下

module.exports = {
    css: {
        loaderOptions: {
            postcss: {
                plugins: [
                    require('postcss-pxtorem')({
                        rootValue: 37.5,
                        propList: ['*']
                    })
                ]
            }
        }
    },
}

2、或在.postcssrc.js或postcss.config.js中配置如下:

module.exports = {
            "plugins": {
                     autoprefixer: {},
                'postcss-pxtorem': {
                    rootValue: 75, //设计稿宽度的1/10。
                    propList: ['*'] //需要做转化处理的属性,如 height weidth margin 等,*表示全部
                }
            }
        }
5. 配置完之后我们就可以在项目中以px为单位去开发了,是的,不用我们手动敲rem转换去开发了,PS设计稿的宽度以750px为基准,否则需要自己调一下,开发时稿子是1px,你就写1px就好了,插件会帮我们换算成rem。
6实际的项目中,你测量的px是多少,就直接写多少px,转化为rem,无需自己计算

感谢以下链接支持
https://blog.csdn.net/weixin_42063951/article/details/127734001
https://blog.csdn.net/Orange71234/article/details/131329898

上一篇 下一篇

猜你喜欢

热点阅读