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",
              },
            },
          });
        });
      },
    },
  },
};
相关推荐
然我18 分钟前
不用 Redux 也能全局状态管理?看我用 useReducer+Context 搞个 Todo 应用
前端·javascript·react.js
前端小巷子23 分钟前
Web 实时通信:从短轮询到 WebSocket
前端·javascript·面试
神仙别闹26 分钟前
基于C#+SQL Server实现(Web)学生选课管理系统
前端·数据库·c#
web前端神器33 分钟前
指定阿里镜像原理
前端
枷锁—sha37 分钟前
【DVWA系列】——CSRF——Medium详细教程
android·服务器·前端·web安全·网络安全·csrf
枷锁—sha39 分钟前
跨站请求伪造漏洞(CSRF)详解
运维·服务器·前端·web安全·网络安全·csrf
群联云防护小杜1 小时前
深度隐匿源IP:高防+群联AI云防护防绕过实战
运维·服务器·前端·网络·人工智能·网络协议·tcp/ip
DanB241 小时前
html复习
javascript·microsoft·html
汉得数字平台1 小时前
【鲲苍提效】全面洞察用户体验,助力打造高性能前端应用
前端·前端监控
花海如潮淹1 小时前
前端性能追踪工具:用户体验的毫秒战争
前端·笔记·ux