1.vant建议使用按需引入
安装babel-plugin-import ,他是一款 babel 插件,它会在编译过程中将 import 的写法自动转换为按需引入的方式
在babel.config.js里写入
module.exports = { presets: [ '@vue/cli-plugin-babel/preset', ], plugins: [ ['import', { libraryName: 'vant', libraryDirectory: 'es', style: true, }, 'vant'], ],};在创建的放插件的plugin文件夹里引入vant.js,在vant.js里写需要的组件
import Vue from 'vue';import { Button, NavBar, Dialog, Toast, Field, Cell, CellGroup, ImagePreview, Image, Lazyload, PullRefresh, Popup, Rate,} from 'vant';Vue.use(NavBar) .use(Button) .use(Dialog) .use(Toast) .use(Field) .use(Cell) .use(CellGroup) .use(ImagePreview) .use(Image) .use(Lazyload) .use(PullRefresh) .use(Popup) .use(Rate);Toast.setDefaultOptions({ position: 'bottom' });在需要的页面直接可以使用
2.vant全部引入
不需要安装按需引入的插件,如安装需要卸载
在创建的放插件的plugin文件夹里引入vant.js,在vant.js里写以下代码
// ***配置按需引入后将不允许直接导入所有组件;// 导入所有组件;import Vue from 'vue';import Vant from 'vant';import 'vant/lib/index.css';Vue.use(Vant);此时已全部引入vant组件,在需要的页面直接可以使用
移动端适配
在index.html页面写入以下代码
<script>(function(win) {var docEl = win.document.documentElement;var time = null;function refreshRem() {var width = docEl.getBoundingClientRect().width;if (width > 414) { // 最大宽度width = 414;}// 将屏幕宽度分成3.75份, 1份为1rem,1rem=100px 具体看UI页面的尺寸var rem = width /3.75;if (rem > 100) {rem = 100;}docEl.style.fontSize = rem + 'px';}win.addEventListener('resize', function() {clearTimeout(time);time = setTimeout(refreshRem, 1);}, false);win.addEventListener('pageshow', function(e) {if (e.persisted) {clearTimeout(time);time = setTimeout(refreshRem, 1);}}, false);refreshRem();})(window);</script>
当页面尺寸更新或者页面展示时会自动计算页面的font-size,这是适配的基础,这种情况下以375尺寸为基础,font-size=100px,在写代码时需要将ui的尺寸转换为rem写入代码,
注意,如果想省事可以使用postcss-pxtorem,他是PostCSS的插件,用于将像素单元生成rem单位。
在项目中安装依赖
npm install postcss-pxtorem -D
2.设置规则(更改postcss.config.js如果没有可以创建,该文件为使用vue-cli3自动创建的文件)
module.exports = { plugins: { autoprefixer: {}, 'postcss-pxtorem': { rootValue: 100, // 结果为:设计稿元素尺寸/100,比如元素宽375px,最终页面会换算成 3.75rem propList: ['*'], }, },};
这样就可以将页面中的px自动转化为rem。