在vue中使用swiper轮播图(搭配watch和$nextTick())

在组件中使用轮播图展示图片信息:

1.下载swiper,5版本为稳定版本

cnpm install swiper@5

2.在组件中引入swiper包和对应样式,若多组件使用swiper,可以把swiper引入到main.js入口文件中:

import 'swiper/css/swiper.css' //引入swiper样式

import Swiper from 'swiper'; //引入swiper

3.在组件中使用:

由于我的组件获取的图片信息由axios请求后端获得,所以要借助属性监听+$nextTick()共同实现轮播图:

html 复制代码
<template>
  <div class="list-container">
    <div class="sortList clearfix">
      <div class="center">
        <!--banner轮播-->
        <div class="swiper-container" ref="mySwiper">
          <div class="swiper-wrapper">
            <div
              class="swiper-slide"
              v-for="carousel in bannerList"
              :key="carousel.id"
            >
              <img :src="carousel.imgUrl" />
            </div>
          </div>
          <!-- 如果需要分页器 -->
          <div class="swiper-pagination"></div>

          <!-- 如果需要导航按钮 -->
          <div class="swiper-button-prev"></div>
          <div class="swiper-button-next"></div>
        </div>
      </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {mapState} from 'vuex'
  import Swiper from 'swiper';
  export default {
    name: 'ListContainer',
    mounted(){
      //在vuex仓库中把轮播图和banner图片取出来
      this.$store.dispatch('BannerList')
    },
    computed:{
      ...mapState({
        bannerList:(state)=>state.home.bannerList
      })
    },
    watch:{
      bannerList:{
        handler(newValue,oldValue){
          this.$nextTick(()=>{
            var mySwiper=new Swiper(this.$refs.mySwiper,{
                //配置分页器内容
                loop: true, // 循环模式选项
                pagination:{
                    el:".swiper-pagination",//换页器与哪个标签关联
                    clickable:true//分页器是否可以点击
                },
                // 如果需要前进后退按钮
                navigation: {
                    nextEl: '.swiper-button-next',
                    prevEl: '.swiper-button-prev',
                },
                //如果需要滚动条
                scrollbar: {
                    el: '.swiper-scrollbar',
                },
          })
        })
      }
    }
    }
  }


</script>

<style lang="less" scoped>
</style>
相关推荐
晓13137 分钟前
【Cocos Creator 2.x】篇——第二章 入门
javascript·游戏引擎
AI_零食1 小时前
鸿蒙PC Electron跨平台应用开发:24时区时间表应用详解
前端·华为·electron·开源·harmonyos·鸿蒙
Electrolux2 小时前
[onlyoffice-v9]纯前端怎么实现编辑预览office
前端·javascript·github
VidDown2 小时前
Webhook 调试器:让第三方回调“原形毕露”
java·开发语言·javascript·编辑器·postman
码云之上2 小时前
聊聊如何设计一个高效、稳定的 Node.js 接入层
前端·后端·node.js
kyriewen3 小时前
我读了一遍 Babel 编译后的 async/await,终于搞懂了它的原理(附 20 行手写实现)
前端·javascript·面试
IT_陈寒3 小时前
Vite项目build后路由404了?你可能漏了这个小配置
前端·人工智能·后端
lichenyang4533 小时前
AI 聊天从纯文本到结构化卡片:SSE done 帧携带 card + 历史记录卡片恢复实战
前端
梦曦i4 小时前
@meng-xi/vite-plugin v0.1.5:告别手动 import,精简工具层
前端
梦曦i4 小时前
Vite 0.1.6重磅更新:智能导入+路由安全
前端