Reputation: 67
I am trying to use Swiper with "vue": "^2.6.11"
, but it throws runtime errors. I followed the guide from https://swiperjs.com/vue, and changed the imports to:
// Import Swiper Vue.js components
import { Swiper, SwiperSlide } from 'swiper/vue/swiper-vue.js';
// Import Swiper styles
import 'swiper/swiper-bundle.css';
Error message:
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
Upvotes: 2
Views: 9542
Reputation: 17438
Make some additions for @tony19's good answer.
Here is a demo example project: Live Demo
<script>
import Swiper, { Navigation, Pagination, Autoplay } from 'swiper'
import 'swiper/swiper-bundle.min.css'
export default {
data() {
return {
activeIndex: 0,
}
},
mounted() {
const SECOND = 1000 // milliseconds
new Swiper(this.$refs.swiper, {
modules: [Navigation, Pagination, Autoplay],
loop: true,
autoplay: {
delay: 3 * SECOND,
disableOnInteraction: false,
},
speed: 2 * SECOND,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
on: {
slideChange: (swiper) => {
this.activeIndex = swiper.realIndex
},
},
})
},
}
</script>
Upvotes: 4
Reputation: 138366
The Swiper components only work with Vue 3. Those components cannot be used in Vue 2, but the Swiper API can be used directly instead:
Apply a template ref on the target Swiper container element in the template.
In the component's mounted()
hook, initialize an instance of Swiper
, passing the template ref and Swiper options that include selectors for the pagination/navigation elements in the template.
<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>
Upvotes: 12