swiper/vue 獲取 swiper實(shí)例方法詳解
在Vue3中使用swiper/vue,如何獲取swiper的組件實(shí)例? 在項(xiàng)目中使用到 swiper/vue,想調(diào)用slideTo方法,發(fā)現(xiàn)通過(guò)refs的方法,拿不到swiper實(shí)例。
<template>
<swiper
ref="swiperRef"
class="promotion-activity-swiper"
:modules="modules"
:space-between="5"
:initialSlide="2"
slides-per-view="auto"
:free-mode="true"
:pagination="{ clickable: true }"
>
<swiper-slide>
</swiper-slide>
</swiper>
</template>
<script setup>
import { reactive, onMounted, watch, ref } from 'vue';
import { Swiper, SwiperSlide } from 'swiper/vue'
import { FreeMode } from 'swiper/modules'
import 'swiper/css'
import 'swiper/css/free-mode'
const swiperRef = ref(null)
onMounted(()=> {
console.log(swiperRef.value)
swiperRef.value.slideTo(3)
})
</script>通常我們想獲取VUE實(shí)例,會(huì)如上面實(shí)例,swiperRef = ref(null),再調(diào)用swiperRef.value就能拿到實(shí)例,但是這樣調(diào)用不了 swiperRef.value.slideTo() 方法,會(huì)報(bào)錯(cuò)slideTo方法不存在。
在網(wǎng)上搜了一下如何調(diào)用swiper實(shí)例,大部分都是通過(guò) swiperRef = new Swiper(‘.swiper’, options) 這種方法初始化swiper,然后直接能用 swiperRef 實(shí)例。這種方法需要自己定義一個(gè)div通過(guò)類(lèi)名去初始化,與我直接調(diào)用 Swiper 組件不一樣。
解決方法:
查看了swiper官方文檔,這里在VUE中使用swiper有給出獲取實(shí)例的方法,
<template>
<swiper
@swiper="setSwiper"
class="promotion-activity-swiper"
:modules="modules"
:space-between="5"
:initialSlide="2"
slides-per-view="auto"
:free-mode="true"
:pagination="{ clickable: true }"
>
<swiper-slide>
</swiper-slide>
</swiper>
</template>
<script setup>
import { reactive, onMounted, watch, ref } from 'vue';
import { Swiper, SwiperSlide } from 'swiper/vue'
import { FreeMode } from 'swiper/modules'
import 'swiper/css'
import 'swiper/css/free-mode'
const swiperRef = ref(null)
// 將swiper實(shí)例賦值給swiperRef
const setSwiper = (swiper)=> {
swiperRef.value = swiper
}
onMounted(()=> {
swiperRef.value.slideTo(3)
})
</script>重點(diǎn)在于 @swiper=“setSwiper”, 參數(shù)就是swiper實(shí)例,setSwiper方法在mounted之前就會(huì)執(zhí)行。
到此這篇關(guān)于swiper/vue 獲取 swiper實(shí)例方法的文章就介紹到這了,更多相關(guān)vue 獲取 swiper實(shí)例內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue3 setup中defineEmits與defineProps的使用案例詳解
在父組件中定義String、Number、Boolean、Array、Object、Date、Function、Symbol這些類(lèi)型的數(shù)據(jù),使用defineEmits會(huì)返回一個(gè)方法,使用一個(gè)變量emits(變量名隨意)去接收,本文給大家介紹vue3 setup中defineEmits與defineProps的使用案例,感興趣的朋友一起看看吧2023-10-10
解決Vite打包后直接使用瀏覽器打開(kāi),顯示空白問(wèn)題
這篇文章主要介紹了解決Vite打包后直接使用瀏覽器打開(kāi),顯示空白問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
element用腳本自動(dòng)化構(gòu)建新組件的實(shí)現(xiàn)示例
本文主要介紹了element-ui的用腳本自動(dòng)化構(gòu)建新組件的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12
關(guān)于Ant-Design-Vue快速上手指南+排坑
這篇文章主要介紹了關(guān)于Ant-Design-Vue快速上手指南+排坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
el-table實(shí)現(xiàn)搜索高亮展示并滾動(dòng)到元素位置的操作代碼
這篇文章主要介紹了el-table實(shí)現(xiàn)搜索高亮展示并滾動(dòng)到元素位置,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2024-01-01

