在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>
相关推荐
@菜菜_达1 天前
前端 HTML 入门(标签)
前端·html
智航GIS1 天前
7.1 自定义函数
前端·javascript·python
BlackWolfSky1 天前
React中文网课程笔记1—快速入门
前端·笔记·react.js
A_one20101 天前
利用npm内置命令构建脚本工具
前端·npm·node.js
哔哩哔哩技术1 天前
2025年哔哩哔哩技术精选技术干货
前端·后端·架构
霍理迪1 天前
CSS布局方式——定位
前端·css
星光不问赶路人1 天前
TypeScript 架构实践:从后端接口到 UI 渲染数据流的完整方案
前端·vue.js·typescript
ttyyttemo1 天前
Dagger技术的使用学习
前端
IT_陈寒1 天前
Redis性能翻倍的5个关键策略:从慢查询到百万QPS的实战优化
前端·人工智能·后端
码界奇点1 天前
基于React与TypeScript的后台管理系统设计与实现
前端·c++·react.js·typescript·毕业设计·源代码管理