官方文档 Vant - Mobile UI Components built on Vue
基本使用
安装
npm i vant -S
npm i babel-plugin-import -D //这是一个插件 按需引入时必须要引入
全局导入 main.js
import Vant from 'vant';
import 'vant/lib/index.css';
Vue.use(Vant);
自动按需引入
// babel.config.js 中配置 babel7
module.exports = {
plugins: [
['import', {
libraryName: 'vant',
libraryDirectory: 'es',
style: true
}, 'vant']
]
}
// 直接引入vant组件
import { Button } from 'vant';
Rem 布局适配
- postcss-pxtorem 是一款 PostCSS 插件,用于将 px 单位转化为 rem 单位
- lib-flexible 用于设置 rem 基准值
安装 postcss-pxtorem
npm install postcss-pxtorem -D
//在vue.config.js配置 vue-cli 3.0以上
css: {
loaderOptions: {
postcss: {
plugins: [
require('postcss-pxtorem')({
rootValue: 37.5, // 换算的基数为设计稿750px的十分之一,为了还原vant、mint-ui的组件,要再除以二。在写样式时,也将值改为设计图的一半。
selectorBlackList: ['weui', 'mu'], // 忽略转换正则匹配项
propList: ['*'],
}),
]
}
}
}
注:
- 这里设计稿为750px,rootValue换算为设计稿的十分之一75。设置成37.5是为了还原vant,Vant 默认使用
px
作为样式单位。 - 在书写其他样式时,注意为设计稿的一半尺寸。
- 如果设计稿的尺寸不是 750px,而是其他大小,可以将
rootValue
配置按情况调整:
rootValue({ file }) {
return file.indexOf('vant') !== -1 ? 37.5 : 75;
},
安装lib-flexible
npm i lib-flexible --save
// main.js
import 'lib-flexible/flexible'
使用问题
- Toast 组件会自动在 Vue 的 prototype 上挂载
$toast
方法,在组件内调用:
// 基本提示
this.$toast('提交成功');
// 自定义图标
this.$toast({
message: '自定义图片',
icon: 'https://img01.yzcdn.cn/vant/logo.png',
});
// 自定义加载
const toast = this.$toast.loading({
message: '提交中',
forbidClick: true,
loadingType: 'spinner',
duration: 0
});
// 关闭加载
toast.clear();
- 在html 和 body 标签上添加
height: 100%
样式,可以防止 List 一直触发加载的问题。
html,
body {
width: 100%;
height: 100%;
}
- 表单内button,如果不是提交按钮,要设置 native-type="button" ,否则都会触发提交事件。或者不要套用<van-form></van-form>。
<van-button round block type="info" native-type="button" color="#FFA218" :disabled="nextDisabled" @click="toSetPwd">下一步</van-button>
- Tab标签页,点击事件绑定事件id,通过name标识符。
<van-tab v-for="(item, i) in photoList" :key="i" :name="item.id">
</van-tab>
- list初始化后会加载一次onLoad事件,如果不想加载,添加:immediate-check="false"关闭初始化的第一次加载。
<van-list
v-model="loading"
:finished="finished"
finished-text="没有更多了"
@load="getSearchList"
:immediate-check="false"
>
</van-list>
- ImagePreview图片预览本身没有挂载在vue的原型上,为了方便使用,可以在main.js中全局引入并挂载。
// 图片预览 import { ImagePreview } from 'vant' Vue.use(ImagePreview) Vue.prototype.ImagePreview = ImagePreview
组件中这么调用:
// 预览图片 preview(index) { let images = [] let picList = this.reportDetail.pic if(picList.length > 0) { picList.forEach((item) => { images.push(item.host + item.dir + item.filepath + item.filename) }) } this.ImagePreview({ images: images, startPosition: index // 指定图片的初始位置(索引值) }) }