vue 实现移动端与网页端自适应

vue 移动端

问题描述:vue怎么在不同屏幕上做根据不同屏幕大小适配

  1. 介绍
    使用amfe-flexiblepostcss-pxtorem 结合的方式
    amfe-flexible:是配置可伸缩布局方案,主要是将1rem设为viewWidth/10
    postcss-pxtorem:postcss的插件,用于将像素单位生成rem单位
  2. 使用方式
    (1)安装amfe-flexiblepostcss-pxtorem
    npm install amfe-flexible --save
    npm i postcss-pxtorem@5.1.1  --save  //这个要装5.1.1版本的
    
    (2)引入:在main.js中引入
    import 'amfe-flexible';
    
    (3)配置postcss-pxtorem
    配置postcss-pxtorem,可在vue.config.js.postcssrc.jspostcss.config.js其中之一配置,权重从左到右降低,没有则新建文件,只需要设置其中一个即可;
    vue.config.js 配置的代码配置如下
    module.exports = {
          
          
        //...其他配置
        css: {
          
          
            loaderOptions: {
          
          
                postcss: {
          
          
                    plugins: [
                        require('postcss-pxtorem')({
          
          
                            rootValue: 37.5,
                            propList: ['*']
                        })
                    ]
                }
            }
        },
    }
    
    ② 在.postcssrc.jspostcss.config.js中配置如下:
    module.exports = {
          
          
        "plugins": {
          
          
            'postcss-pxtorem': {
          
          
                rootValue: 37.5,
                propList: ['*']
            }
        }
    }
    

注意:

rootValue根据设计稿宽度除以10进行设置,这边假设设计稿为375,即rootValue设为37.5
propList是设置需要转换的属性,这边*为所有都进行转换。

比如项目中我们这样写:

.login-form {
    
    
    width: 90%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    padding: 20px;
    box-sizing: border-box;
    border-radius: 10px;
    .title {
    
    
      position: absolute;
      top: -50px;
      font-size: 24px;
      color: #fff;
      left: 0;
      right: 0;
      text-align: center;
    }
  }

那我们代码的产出就是下面这样的 ,插件实惠帮我们自动转换单位

login-wraper .login-form {
    
    
    width: 90%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    background-color: #fff;
    padding: .53333rem; // 注意这个就是转换后的单位
    box-sizing: border-box;
    border-radius: .26667rem;  // 注意这个就是转换后的单位
}

转发链接:https://juejin.cn/post/7008180094208311303

猜你喜欢

转载自blog.csdn.net/weixin_44021888/article/details/131175921