无法将 Swiper 与 "vue" 一起使用:“^2.6.11”

Cannot use Swiper with "vue": "^2.6.11"

我正在尝试将 Swiper 与 "vue": "^2.6.11" 一起使用,但它会引发运行时错误。我遵循了 https://swiperjs.com/vue 的指南,并将导入更改为:

// Import Swiper Vue.js components
import { Swiper, SwiperSlide } from 'swiper/vue/swiper-vue.js';

// Import Swiper styles
import 'swiper/swiper-bundle.css';

错误信息:

Property or method "onSwiper" is not defined on the instance but referenced during render, Invalid handler for event "swiper": got undefined , Failed to mount component: template or render function not defined

Swiper components only work with Vue 3。这些组件不能在 Vue 2 中使用,但是 Swiper API 可以直接使用:

  1. 在模板中的目标 Swiper 容器元素上应用 template ref

  2. 在组件的 mounted() hook, initialize an instance of Swiper 中,传递模板引用和 Swiper 选项,其中包括模板中 pagination/navigation 元素的选择器。

<script>
import Swiper, { Navigation, Pagination } from 'swiper'
import 'swiper/css'
import 'swiper/css/navigation'
import 'swiper/css/pagination'

export default {
  mounted() {
    2️⃣
    new Swiper(this.$refs.swiper, {
      // configure Swiper to use modules
      modules: [Navigation, Pagination],
      // Optional parameters
      loop: true,

      // If we need pagination
      pagination: {
        el: '.swiper-pagination',
      },

      // Navigation arrows
      navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
      },

      // And if we need scrollbar
      scrollbar: {
        el: '.swiper-scrollbar',
      },
    })
  },
}
</script>

<template>
  <!-- Slider main container -->
  <div 1️⃣ ref="swiper" class="swiper">
    <!-- Additional required wrapper -->
    <div class="swiper-wrapper">
      <!-- Slides -->
      <div class="swiper-slide">Slide 1</div>
      <div class="swiper-slide">Slide 2</div>
      <div class="swiper-slide">Slide 3</div>
    </div>
    <!-- If we need pagination -->
    <div class="swiper-pagination"></div>

    <!-- If we need navigation buttons -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>

    <!-- If we need scrollbar -->
    <div class="swiper-scrollbar"></div>
  </div>
</template>

<style scoped>
.swiper-slide {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

demo