1.安裝Vant
# 通過 npm 安裝
npm i vant -S
# 通過 yarn 安裝
yarn add vant
2.安裝babel 插件
按照官網(wǎng)上寫的,安裝babel 插件后瘦癌,就能在編譯過程中將 import 的寫法自動轉換為按需引入的方式
# 安裝插件
npm i babel-plugin-import -D
官網(wǎng)上說在.babelrc 中添加配置
{
"plugins": [
["import", {
"libraryName": "vant",
"libraryDirectory": "es",
"style": true
}]
]
}
不過在項目里發(fā)現(xiàn).babelrc文件中還有其他內(nèi)容
"plugins": ["transform-vue-jsx", "transform-runtime"]
都是字符串艾帐,和需要添加的格式不大一樣乌叶。沒關系,直接加在后面就好柒爸。加好后的就是這樣:
"plugins": ["transform-vue-jsx", "transform-runtime",
[
"import",
{
"libraryName": "vant",
"libraryDirectory": "es",
"style":true
}
]
]
3.在頁面里引用
import { Button } from 'vant';
官網(wǎng)到這就完了准浴。但是你會發(fā)現(xiàn)一運行還是報錯,
還得把組件注冊一下捎稚。
用了Vux組件庫的伙伴會習慣這樣寫
components: { Grid, GridItem }
一運行還是報錯乐横,那是因為使用的vux模板已經(jīng)幫忙處理好了。
而對于Vant正確寫法應該是
components: {
[Grid.name]: Grid,
[GridItem.name]: GridItem
}
頁面完整內(nèi)容就是
<template>
<div class="wrapper">
<van-grid :column-num="3">
<van-grid-item v-for="value in 6" :key="value" icon="photo-o" text="文字"/>
</van-grid>
</div>
</template>
<script>
import { Grid, GridItem } from "vant";
export default {
components: {
[Grid.name]: Grid,
[GridItem.name]: GridItem
},
props: {},
data() {
return {};
},
methods: {}
};
</script>