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",
              },
            },
          });
        });
      },
    },
  },
};
相关推荐
DevOpenClub6 分钟前
网页证据如何长期复核:快照、静态 HTML 与 PDF 归档链路
前端·pdf·html
独立开发之道12 分钟前
Three.js 创建 VR 内容:四步把一个普通 3D 场景送进头显
javascript·3d·vr
Canace27 分钟前
基于 Codex Agent Harness 套壳实现自己的 AI 产品:Agent 运行时与任务编排实践
前端·人工智能·agent
星栈独行1 小时前
自定义 UI-UX-Pro-Max 的 CSV 知识库,把 AI 生成的后台拉回行业该有的样子
前端·人工智能·ui·ux
hunterandroid1 小时前
[Android 从零到一] APK 体积优化实战:从 50MB 到 15MB 的瘦身之旅
android·前端
Coodor1 小时前
在前端如何转换IC卡卡号格式
前端·javascript·nfc·卡号格式
invicinble1 小时前
数字系统--c端数字环境入口和操作系统
前端
hunterandroid1 小时前
[鸿蒙从零到一] relationalStore 高级实战:事务、版本迁移与数据库加密
前端
百慕大三角1 小时前
给 SPA 加页面切换动画:View Transitions API 从入门到实战
前端·javascript
不可能片场1 小时前
自动化也会丢:一次 WorkBuddy 自动化清空的复盘
前端·electron