vue中swiper轮播图的使用

1.引包

说明:导入相应js引css

import "Swiper" from "swiper"

import "swiper/css/swiper.css";

import "swiper/js/swiper";

2.结构

说明:必要的结构使用;直接封装成一个组件

html 复制代码
<template>
        <div class="swiper-container" ref="cur">
          <div class="swiper-wrapper">
            <div
              class="swiper-slide"
              v-for="carousel in list"
              :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>
</template>

3.new Swiper实例

说明:(页面当中务必要有结构);注释已经写入代码。

第一:可以解决获取数据在Swiper实例之前;第二:可以解决v-for遍历完后在Swiper之前。

javascript 复制代码
import Swiper from "swiper";
export default {
  name: "Carousel",
  props: ["list"],
  // 这样做的目的是在list属性发生变化时,
  // 能够及时更新Swiper轮播组件,以保证轮播的内容和效果与list属性的变化保持同步。
  watch: {
    list: {
      immediate: true,
      handler(newValue, oldValue) {
        // 这里有了数据还是不行,v-for有没有渲染也是问题,不能保证结构是否完成。
        // 用于在DOM更新后执行回调函数。在Vue中,当对数据进行修改后,DOM并不会立即更新,而是在下一个"tick"时进行更新。
        // 这个"tick"是Vue内部的更新队列,在执行用户逻辑之前进行DOM更新。
        this.$nextTick(function () {
          const mySwiper = new Swiper(this.$refs.cur, {
            loop: true,
            slidesPerView: "auto",
            slidesPerGroupAuto: true,
            autoplay: true,
            //如果需要分页器
            pagination: {
              el: ".swiper-pagination",
              clickable: true,
              //如果需要前进后退按钮
              navigation: {
                nextEl: ".swiper-button-next",
                prevEl: ".swiper-button-prev",
              },
            },
          });
        });
      },
    },
  },
};
相关推荐
前端 贾公子3 小时前
v-if 与 v-for 的优先级对比
开发语言·前端·javascript
小二·7 小时前
Pinia 完全指南:用 TypeScript 构建可维护、可测试、可持久化的 Vue 3 状态管理
javascript·vue.js·typescript
bug总结7 小时前
Vue3 实现后台管理系统跳转大屏自动登录功能
前端·javascript·vue.js
用户47949283569157 小时前
同事一个比喻,让我搞懂了Docker和k8s的核心概念
前端·后端
烛阴7 小时前
C# 正则表达式(5):前瞻/后顾(Lookaround)——零宽断言做“条件校验”和“精确提取”
前端·正则表达式·c#
C_心欲无痕7 小时前
浏览器缓存: IndexDB
前端·数据库·缓存·oracle
郑州光合科技余经理7 小时前
技术架构:上门服务APP海外版源码部署
java·大数据·开发语言·前端·架构·uni-app·php
GIS之路7 小时前
GDAL 实现数据属性查询
前端
PBitW8 小时前
2025,菜鸟的「Vibe Coding」时刻
前端·年终总结
mwq301239 小时前
不再混淆:导数 (Derivative) 与微分 (Differential) 的本质对决
前端