美文网首页
Vue2中使用Vant组件

Vue2中使用Vant组件

作者: 周星星的学习笔记 | 来源:发表于2022-05-18 14:51 被阅读0次

    前两天在做一个自定义页面的功能模块,中间涉及到预览组件的开发,我就在想中间预览组件能不能用开源的专门做H5端的组件UI库,这样就开发起来就方便很多,不用自己一个个地去写这些组件了,于是就找到了Vant组件 ,感觉用起来还挺方便的,记录一下使用方法。效果如下图:

    自定义页面

    一、安装Vant

    #如果安装有问题,使用cnpm 试一试
    npm i vant@latest-v2 -S
    

    二、配置自动按需引入组件 (推荐)

    1.根目录找到babel.config.js文件,在plugins数组中添加

    module.exports = {
      presets: ['@vue/cli-plugin-babel/preset'],
      plugins: [
        //添加支持按需引入配置
        [
          'import',
          {
            libraryName: 'vant',
            libraryDirectory: 'es',
            style: true
          },
          'vant'
        ]
      ]
    }
    

    三、新建一个专门用来全局注册Vant组件的文件

    1.我这里就建在src/services/vant.js里面

    /**
     * vant 的一些组件的使用
     * 用到什么组件就注册一下 
     */
    /**
     * vant 的一些组件的使用
     */
    import Vue from 'vue'
    import { Lazyload, Swipe, SwipeItem, NoticeBar, Image as VanImage } from 'vant'
    Vue.use(Lazyload)
    Vue.use(Swipe)
    Vue.use(SwipeItem)
    Vue.use(NoticeBar)
    Vue.use(VanImage)
    ...
    

    四、在main.js里面导入vant.js

    //注册全局的Vant组件
    import './services/vant'
    

    五、使用(以轮播图组件为例)

    <template>
      <div class="comp-wrap">
        <van-swipe :autoplay="3000">
          <van-swipe-item v-for="(image, index) in images" :key="index">
            <img v-lazy="image" class="swiper-img" />
          </van-swipe-item>
        </van-swipe>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          images: [
            'https://img01.yzcdn.cn/vant/apple-1.jpg',
            'https://img01.yzcdn.cn/vant/apple-2.jpg'
          ]
        }
      }
    }
    </script>
    
    <style lang="scss" scoped>
    .comp-wrap {
      min-height: 200px;
      background-color: #fff;
      .swiper-img {
        width: 100%;
        height: 200px;
      }
    }
    </style>
    
    

    六、注意事项

    • 配置好了之后,如果出现组件没有样式,需要重启一下工程:npm run serve

    相关文章

      网友评论

          本文标题:Vue2中使用Vant组件

          本文链接:https://www.haomeiwen.com/subject/eoraurtx.html