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
CodePudding user response:
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 ofSwiper, 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" >
<!-- Additional required wrapper -->
<div >
<!-- Slides -->
<div >Slide 1</div>
<div >Slide 2</div>
<div >Slide 3</div>
</div>
<!-- If we need pagination -->
<div ></div>
<!-- If we need navigation buttons -->
<div ></div>
<div ></div>
<!-- If we need scrollbar -->
<div ></div>
</div>
</template>
<style scoped>
.swiper-slide {
display: flex;
justify-content: center;
align-items: center;
}
</style>
