在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>
相关推荐
AI开源软件2 小时前
用MQTT跑通一台模拟设备:看懂IoT产品、物模型和告警
java·vue.js·spring boot·物联网·mqtt·iot·企业管理
qq_274475154 小时前
第 28 篇:Promise 全解析:状态、then/catch/finally、静态方法 all/race/allSettled/any
开发语言·javascript
GuWenyue6 小时前
昵称限 20 字,8 个 emoji 却超长:一个「字」在系统里有四种长度
javascript·数据库·后端
CV-deeplearning6 小时前
Chrome DevTools实战
前端·agent·chrome devtools·mcp
xurileidian6 小时前
第 30 篇 · 边玩边学Python · 猜数字小游戏 把判断循环异常串起来
前端·python·算法
前端精髓6 小时前
三种方式实现 Agent 工具调用:OpenAI、LangChain 与 LangGraph
前端·数据库·langchain
国科安芯7 小时前
光链路捕获的那一刻:商业激光通信终端捕获跟踪伺服与探测前端的低噪声供电
前端·网络·卫星·电源芯片·抗辐照芯片·在轨
一铭111997 小时前
微信小程序可视化搭建实战:模板、组件与发布验收
前端·低代码·微信小程序·小程序·页面设计·可视化搭建·发布验收
LabVIEW开发7 小时前
LabVIEW 2025 新特性盘点:这几个改进,值得你认真看一遍
前端·labview
画中有画9 小时前
自动化脚本中使用RSA
前端·javascript·自动化