Vue + van-swipe 实现图片轮播

图片轮播是我们经常需要用到的功能,一般在首页展示活动海报或者商品信息等,如何实现呢?今天我们借助于 Vant。

效果图:

主要用到:

vue-lazyload( 图片懒加载 )

Vant 的 Swipe 组件现实图片轮播

 

1. 在 main.js 中注册 vue-lazyload 插件 :

import Vuelazyload from 'vue-lazyload';

Vue.use ( Vuelazyload, {
  loading: require('./assets/imgs/loading.svg'),
  error: require('./assets/imgs/error.svg'),
  attempt: 1   
})

注意: 图片的地址根据实际情况自己确定,一定要用 require() 将图片进入进来,否则图片不显示。

 

2. 引用 Vant 的 Swipe 组件:

2.1 引入:

import { Swipe, SwipeItem } from 'Vant'

 

2.2 组件注册:

components: {
  [Swipe.name]: Swipe,
  [SwipeItem.name]: SwipeItem,
}

 

3. data() 中添加图片地址:

data() {
  return {
    imgs: [
      {id: 1, image: '...'}
      {id: 2, image: '...'}
{id: 3, image: '...'} ] } }

 

4. template 中添加:

<!-- 图片轮播 -->
<div class="banner">
  <van-swipe class="my-swipe" :autoplay="2100" indicator-color="green" touchable>
    <van-swipe-item v-for="item of imgs" :key="item.id">
      <img v-lazy="item.image" class="banner-img"/>
    </van-swipe-item>
  </van-swipe>
</div>

 

如果想添加点击轮播图片的事件,只需要添加 @click 即可:

<van-swipe-item v-for="item of imgs" :key="item.id" @click="event">

 

到这里我们就完成了图片轮播的功能。

 

如果文章中有不正确的地方,欢迎大家交流指正。

posted @ 2020-08-27 15:54  几行  阅读(7858)  评论(0编辑  收藏  举报