vant在vue/cli3中局部引入

因爲官網的文檔是給微信小程序的,所以記錄一下。
要注意一下webstorm自動生成的vue模板是vue/cli3,很多教程裏面說的是改.babelrc,但是這個是2.x版本的,3.0應該是直接在babel.config.js下面改就行了。註釋的部分是本來的部分。

// module.exports = {
//   presets: [
//     '@vue/cli-plugin-babel/preset'
//   ]
// }
module.exports = {
  presets: ['@vue/cli-plugin-babel/preset'],
  // vant引入:
  plugins: [
    [
      'import',
      {
        libraryName: 'vant',
        libraryDirectory: 'es',
        style: name => `${name}/style/less`
      },
      'vant'
    ]
  ]
}

然後在main.js裏面引用。

// main.js
import { Button } from 'vant'
Vue.use(Button)

然後組件裏不需要再額外註冊。注意template中只能有一個div包裹全部,template本身不是一個封閉的標籤,否則會報錯。

<template>
  <div class="hello">
    {{msg}}

  <van-button type="default">默認按鈕</van-button>
  <van-button type="primary">主要按鈕</van-button>
  <van-button type="warning">警告按鈕</van-button>
  <van-button type="danger">危險按鈕</van-button>
  </div>
</template>

<script>
export default {

  name: 'index',
  props: {
    msg: String
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

參考:https://juejin.im/post/5e7f549d6fb9a03c6c18f0f1
但是如果引入多了都放在main.js中應該不好看,所以改成一個單獨的組件中,只需要在main.js中引入import '@/components/Vant',然後在components下面創建一個vant的組件,然後引入:
在這裏插入圖片描述

import Vue from 'vue'

// https://youzan.github.io/vant/#/zh-CN/home
import {
    Button,
    Toast,
    Dialog,
    Field,
    Form,
    Notify,
    Cell,
    CellGroup,
    NavBar,
    Search,
    Image,
    Lazyload,
    Swipe,
    SwipeItem,
    Loading,
    Tag,
    CountDown,
    Tabbar,
    TabbarItem,
    List,
    PullRefresh,
    TreeSelect,
    Icon,
    Progress,
    ImagePreview,
    Rate,
    GoodsAction,
    GoodsActionIcon,
    GoodsActionButton,
    Sku,
    AddressList,
    AddressEdit,
    SwipeCell,
    Card,
    SubmitBar,
    Checkbox,
    CheckboxGroup,
    Grid,
    GridItem,
    DropdownMenu,
    DropdownItem,
    ContactCard,
    ContactList,
    ContactEdit
} from 'vant'

Vue.use(Toast)
    .use(Dialog)
    .use(Notify)
    .use(Field)
    .use(Form)
    .use(Button)
    .use(Cell)
    .use(CellGroup)
    .use(NavBar)
    .use(Search)
    .use(Image)
    .use(Lazyload)
    .use(Swipe)
    .use(SwipeItem)
    .use(Loading)
    .use(Tag)
    .use(CountDown)
    .use(Tabbar)
    .use(TabbarItem)
    .use(List)
    .use(PullRefresh)
    .use(TreeSelect)
    .use(Icon)
    .use(Progress)
    .use(ImagePreview)
    .use(Rate)
    .use(GoodsAction)
    .use(GoodsActionIcon)
    .use(GoodsActionButton)
    .use(Sku)
    .use(AddressList)
    .use(AddressEdit)
    .use(SwipeCell)
    .use(Card)
    .use(SubmitBar)
    .use(Checkbox)
    .use(CheckboxGroup)
    .use(Grid)
    .use(GridItem)
    .use(DropdownMenu)
    .use(DropdownItem)
    .use(ContactCard)
    .use(ContactList)
    .use(ContactEdit)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章