Vant是一款移動端基於vue的組件庫,V2.1.1版本非常棒。文檔地址:https://youzan.github.io/vant/?source=vuejsorg#/zh-CN/intro,那么Vant如何使用(以下操作都是基於vue-cli3)
1.如何自動按需引入組件?
《1》安裝插件:npm i babel-plugin-import -D
babel-plugin-import 是一款 babel 插件,它會在編譯過程中將 import 的寫法自動轉換為按需引入
《2》在 babel.config.js 中配置
在 babel.config.js 中配置
module.exports = { plugins: [ ['import', { libraryName: 'vant', libraryDirectory: 'es', style: true }, 'vant'] ] };
《3》在main.js中添加項目中需要用到的組件
例如:
此步驟不能少,不然使用中無效果
2.如何結合flexible做Rem適配?
看官方文檔Vant 中的樣式默認使用px
作為單位,那么既然需要用rem做適配,按下面步驟操作
《1》如何將px單位轉化為rem?
借助postcss-pxtorem插件,postcss-pxtorem 是一款 postcss 插件,用於將單位轉化為 rem。如何操作?
安裝:npm install autoprefixer postcss-pxtorem --save-dev
配置:vue.config.js文件
const autoprefixer = require('autoprefixer') const pxtorem = require('postcss-pxtorem') module.exports = { css: { loaderOptions: { postcss: { plugins: [ autoprefixer(), pxtorem({ rootValue: 37.5, propList: ['*'], // 該項僅在使用 Circle 組件時需要 // 原因參見 https://github.com/youzan/vant/issues/1948 selectorBlackList: ['van-circle__layer'] }) ] } } } }
按以上操作即可
《2》如何做rem適配?
rem適配文檔上建議使用lib-flexible,flexible適配的原理是物理像素與邏輯像素的相互轉化:物理像素px = window.screen.width(邏輯像素pt) * window.devicePixelRatio
如何配合框架使用:
1.安裝
npm i -S amfe-flexible
2.main.js引入
import 'amfe-flexible'
《3》項目中使用?
對於寬度為750px的設計圖,由於rootValue: 37.5為基准,在寫css時候設計圖上文字大小多少像素就寫多少像素即可