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",
              },
            },
          });
        });
      },
    },
  },
};
相关推荐
江城开朗的豌豆1 分钟前
前端性能救星!用 requestAnimationFrame 丝滑渲染海量数据
前端·javascript·面试
江城开朗的豌豆2 分钟前
src和href:这对'双胞胎'属性,你用对了吗?
前端·javascript·面试
江城开朗的豌豆8 分钟前
forEach遇上await:你的异步代码真的在按顺序执行吗?
前端·javascript·面试
万少17 分钟前
HarmonyOS Next 弹窗系列教程(3)
前端·harmonyos·客户端
七灵微1 小时前
【后端】单点登录
服务器·前端
持久的棒棒君5 小时前
npm安装electron下载太慢,导致报错
前端·electron·npm
渔舟唱晚@7 小时前
大模型数据流处理实战:Vue+NDJSON的Markdown安全渲染架构
vue.js·大模型·数据流
crary,记忆7 小时前
Angular微前端架构:Module Federation + ngx-build-plus (Webpack)
前端·webpack·angular·angular.js
漂流瓶jz8 小时前
让数据"流动"起来!Node.js实现流式渲染/流式传输与背后的HTTP原理
前端·javascript·node.js
SamHou08 小时前
手把手 CSS 盒子模型——从零开始的奶奶级 Web 开发教程2
前端·css·web