vue3中使用swiper
13213
·
注意: 使用之前请确定使用的swiper版本,避免走一些不必要的弯路(笔者踩过来的)本文采用的是vue3.0、swiper^6.6.1。
1、安装依赖
npm install swiper
2、vue文件引入
<template>
<swiper :slides-per-view="1" :scrollbar="{ draggable: true }">
<swiper-slide>1</swiper-slide>
<swiper-slide>1</swiper-slide>
<swiper-slide>1</swiper-slide>
</swiper>
</template>
import SwiperCore, { Scrollbar, Pagination } from 'swiper'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/swiper.scss'
import 'swiper/components/scrollbar/scrollbar.scss'
import 'swiper/components/pagination/pagination.scss'
import { ref, defineComponent, reactive, onMounted, toRefs, nextTick } from 'vue'
SwiperCore.use([Scrollbar, Pagination])
export default defineComponent({
name: 'Warhouse',
components: {
Swiper,
SwiperSlide
}
}
按需引入对应的工具,例如Scrollbar, Pagination,并import对应的样式文件
3、在业务中,有可能会要用上swiper整个实例进行一些api操作
根据vue3 ref获取。拿到的实例并未挂载
<template>
<swiper :slides-per-view="1" :scrollbar="{ draggable: true }" ref="mySwiper">
<swiper-slide>1</swiper-slide>
<swiper-slide>1</swiper-slide>
<swiper-slide>1</swiper-slide>
</swiper>
</template>
import SwiperCore, { Scrollbar, Pagination } from 'swiper'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/swiper.scss'
import 'swiper/components/scrollbar/scrollbar.scss'
import 'swiper/components/pagination/pagination.scss'
import { ref, defineComponent, reactive, onMounted, toRefs, nextTick } from 'vue'
SwiperCore.use([Scrollbar, Pagination])
export default defineComponent({
name: 'Warhouse',
components: {
Swiper,
SwiperSlide
},
setup: (){
const mySwiper = ref(null)
return {
mySwiper
},
onMounted(){
console.log(mySwiper)
}
}
}
上面打印结果: 这里访问不到swiper属性与方法
正确获取swiper实例:其实swiper组件抛出了@swiper 需要将一个Swiper实例传递
<template>
<swiper :slides-per-view="1" :scrollbar="{ draggable: true }" @swiper="setControlledSwiper">
<swiper-slide>1</swiper-slide>
<swiper-slide>1</swiper-slide>
<swiper-slide>1</swiper-slide>
</swiper>
</template>
import SwiperCore, { Scrollbar, Pagination } from 'swiper'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/swiper.scss'
import 'swiper/components/scrollbar/scrollbar.scss'
import 'swiper/components/pagination/pagination.scss'
import { ref, defineComponent, reactive, onMounted, toRefs, nextTick } from 'vue'
SwiperCore.use([Scrollbar, Pagination])
export default defineComponent({
name: 'Warhouse',
components: {
Swiper,
SwiperSlide
},
setup: (){
const data = reactive({
controlledSwiper: null
})
const methods = {
setControlledSwiper(swiper){
data.controlledSwiper = swiper
}
}
onMounted(){
console.log(data.controlledSwiper)
}
return {
...toRefs(data),
...methods
},
}
}
下面就可以根据data.controlledSwiper.slideTo(index)... 等调用方法
更多推荐
已为社区贡献1条内容
所有评论(0)