vue 移動端完美適配方案,拿走不謝


1、適配方案

在本項目中我所使用的vue移動方案是使用amfe-flexible 和 postcss-pxtorem 結合)的方式。

首先介紹一下amfe-flexible

amfe-flexible 是配置可伸縮布局方案,主要是將 1rem 設為 viewWidth/10。

然后就是這個庫 postcss-pxtorem

postcss-pxtorem是postcss的插件,用於將像素單元生成rem單位。

2、如何使用和配置?

1、安裝 amfe-flexible 和 postcss-pxtorem

​
npm install amfe-flexible --save
npm i postcss-pxtorem@5.1.1  --save  //這個要裝5.1.1版本的

2、安裝完成后,肯定需要引入才能使用

我們需要在main.js中引入才能使用

import 'amfe-flexible';

這樣引入就OK了

3、然后就是postcss-pxtorem 配置步驟

配置postcss-pxtorem,可在vue.config.js、.postcssrc.js、postcss.config.js其中之一配置,權重從左到右降低,沒有則新建文件,只需要設置其中一個即可:

為了方便 我是在 vue.config.js 配置的代碼配置如下:

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

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

module.exports = {
    "plugins": {
        'postcss-pxtorem': {
            rootValue: 37.5,
            propList: ['*']
        }
    }
}

注意點:

1、rootValue根據設計稿寬度除以10進行設置,這邊假設設計稿為375,即rootValue設為37.5;

2、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;  // 注意這個就是轉換后的單位
}

好了以上就是vue手機端適配方案。拿走不謝。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM