Home > Enterprise >  How to access this.$refs in <script setup> Vue
How to access this.$refs in <script setup> Vue

Time:05-19

I'm trying to replicate enter image description here

You want: const swiper = ref(null);

At least that is my assumption based on your code. If this swiper tool is compatible with vue 3 then in theory that should work.

Since this is a ref, you need to use .value to access it, so you'd want: const handleNextSlide = () => swiper.value.slideNext()

Finally, since you are using typescript, you can do something like const swiper = ref<Swiper | null>(null)

CodePudding user response:

If you want the equivalent to:

computed: {
    swiper() {
        return this.$refs.swiper.swiper;
    }
}

in script setup, you just need to:

<script setup>
import { computed, ref } from "vue";
...

const swiper  = ref(null)

// .swiper will only work if the ref swiper (Swiper element) has a property named swiper
const swiperComputed = computed(() => swiper.value.swiper)

...
</script>

<template>
  <Swiper ref="swiper">
    <SwiperSlide>1</SwiperSlide>
    <SwiperSlide>2</SwiperSlide>
    <SwiperSlide>3</SwiperSlide>
    <SwiperSlide>4</SwiperSlide>
    <SwiperSlide>5</SwiperSlide>
  </Swiper>
</template>

  • Related