Ways to utilize this.$refs within the <script setup> Vue section

Attempting to recreate this using the <script setup> tag without the use of the this keyword.

Template (from original code)

<swiper ref="swiper">
    <swiper-slide></swiper-slide>
    <swiper-slide></swiper-slide>
</swiper>

<a class="swiper-navigation is-previous" @click="swiper.slidePrev()"></a>
<a class="swiper-navigation is-next" @click="swiper.slideNext()"></a>

Script (from original code)

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

Attempted to utilize getCurrentInstance() but for some reason getCurrentInstance().refs returns an empty object {} even though it's present when I use

console.log(getCurrentInstance())
.

My <script setup> component

<script setup lang="ts">

import { Swiper, SwiperSlide } from 'swiper/vue';

const swiper = // ???

const handleNextSlide = () => swiper.slideNext()
const handlePrevSlide = () => swiper.slidePrev()

</script>


<template>

<div>

    <button @click="handlePrevSlide()">Prev</button>
    <button @click="handleNextSlide()">Next</button>

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

</div>

</template>

Answer №1

For an alternative approach to achieve the same functionality as:

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

using script setup, follow these steps:

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

const swiper  = ref(null)

// .swiper requires the ref swiper (Swiper element) to have 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>

Answer №2

For more information on template refs in vue, take a look at the vue documentation here: https://vuejs.org/guide/essentials/template-refs.html#accessing-the-refs

Remember to specify the API reference as "composition api":

https://i.sstatic.net/uT7M8.png

If you need to define a swiper variable, you can do so like this: const mySwiper = ref(null);

Based on your code, it seems that you are trying to use the swiper tool in vue 3, which should work theoretically.

Since swiper is a ref, make sure to access it using .value, for example:

const goToNextSlide = () => mySwiper.value.slideNext()

In typescript, you can define swiper with specific types like this:

const mySwiper = ref<Swiper | null>(null)

Answer №3

When working with refs in the context of the Options API, it is essential to wait for the mounted() hooks.

Keep in mind that accessing the ref is only possible after the component has been fully mounted.

Additional tip: You can also utilize the onMounted(() => {}) hook.

For more information, refer to the documentation: https://vuejs.org/guide/essentials/template-refs.html#accessing-the-refs

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transferring data from Node.js server to React client with axios communication

I have a project in the works that involves tracking chefs and their new recipes. I am developing a simple frontend application where users can input a chef's username, which will then be sent to the backend for scraping several cooking websites to re ...

Having trouble grouping data on website due to duplicate names

Currently in the process of scraping data from various websites and looping through it. Specifically focusing on scraping the head section. This is an example illustrating the structure of the data: const head = { rel_data: [ { rel: &quo ...

Creating an Android game with the utilization of HTML5 and Javascript involves the adaptation of images to various screen resolutions

Currently, I am working on creating a basic game for android devices by utilizing HTML5, javascript, and cordova for wrapping it up. One of the key features of my game will involve using an image as a background and animating it to create a dynamic visua ...

Vue components not responding to TailwindCSS breakpoints as expected

After successfully integrating Tailwind into my Vue project and ironing out the initial kinks, I am now facing a roadblock. Despite having code completion in VS Code, I am unable to utilize breakpoints within my project. <div class="container mx-auto"& ...

What are the benefits of utilizing Vue CLI with Babel and ESLint?

As I navigate my way into the world of Node.js and Vue.js, I came across the Vue CLI tooling kit which includes a scaffolding project along with ESLint and Babel. The question that arises in my mind is: what exactly is the purpose of Vue's Babel tool, ...

Switch the date format to 'YYYY-MM-DD' when using the DateRangePicker

$('#reportrange').daterangepicker({ startDate: start, endDate: end, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract ...

Error occurred due to an invalid element type with the imported React component

Using a component imported from an npm package in two different apps has resulted in unexpected behavior. In one app, the component functions perfectly as expected. However, in the other app, an error is raised: Element type is invalid: expected a string ...

Using type annotations is restricted to TypeScript files only, as indicated by error code ts(8010)

I encountered an issue with React.MouseEvent<HTMLElement> const handleOpenNavMenu = (event: React.MouseEvent<HTMLElement>) => { setAnchorElNav(event.currentTarget); }; const handleOpenUserMenu = (event: React.MouseEvent<HTMLElement ...

Creating a Click Counter with jQuery 2.0.1/2.0.2: A Step-by-Step Guide

Currently in the process of creating a fundraising webpage for charity, I have chosen to display an animated rabbit making its way Around The World. My progress so far includes a non-looping gif that plays on click, with a limitation on how often it can b ...

Tips for storing multiple objects in local storage without replacing the existing data

I want to store this information in local storage without overwriting the existing data. Instead, I would like to append it to the object created in local storage using JavaScript code function addToCartClicked(event) { var button = event.target v ...

Grouping elements of an array of objects in JavaScript

I've been struggling to categorize elements with similar values in the array for quite some time, but I seem to be stuck Array: list = [ {id: "0", created_at: "foo1", value: "35"}, {id: "1", created_at: "foo1", value: "26"}, {id: "2", cr ...

Utilize the double parsing of JSON information (or opt for an alternative technique for dividing the data

Looking for the most effective approach to breaking down a large data object retrieved from AJAX. When sending just one part (like paths), I typically use JSON.parse(data). However, my goal is to split the object into individual blocks first and then parse ...

Executing a function in Javascript following two callback functions

Help needed with handling JavaScript callback functions. I am currently using node Js and node-mysql for mysql queries in my application. The issue arises when new users register, as I need to perform 2 database checks: one to see if the email is already ...

Enhance Vue functionality by adding a versatile mutation that can be utilized across

I am facing a challenge where I have a mutation that needs to be reused in multiple Vuex modules but should only modify the state at each module level. Is there a way to separate out this mutation so it can be easily added to each module's mutations w ...

"Typescript React encounters issues with recognizing props handed over to a functional component, resulting in error code ts 274

Currently, I am engaged in a react project that involves typescript. The goal is to exhibit movie character details obtained from an API through individual cards for each character. This should be achieved by utilizing react functional components along wi ...

Important notice: Warning for stand-alone React 18 page regarding the import of createRoot from "react-dom"

I am in the process of developing a standalone webpage utilizing React 18: <!DOCTYPE html> <html lang="en"> <head> <title>Hello React!</title> <script crossorigin src="https://unpkg.com/react@1 ...

Creating a transcluding element directive in AngularJS that retains attribute directives and allows for the addition of new ones

I've been grappling with this problem for the past two days. It seems like it should have a simpler solution. Issue Description The objective is to develop a directive that can be used in the following manner: <my-directive ng-something="somethi ...

Using SetTimeout with the TextInput component in a React-Native application

Currently, I am working on creating a SearchBar component for my new Android application using React-Native. As a newcomer to React-Native, I created a function called _changeInput() to handle passing text to a local function. Initially, the text pass wor ...

Utilizing AngularJS to invoke REST API calls within a for loop and efficiently manage priority for the visible content area

Currently, I am dealing with an array containing over 400 data IDs related to different fruits. My goal is to make API calls in a for loop to retrieve relevant information about each fruit. While this works fine for smaller lists, it fails when dealing wit ...

Create an array of routes specifically for private access using Private Route

In my application, I have defined different routes for admins, employees, and clients. Admins can access routes /x, /y, and /z, employees can access routes /a and /b, and everyone including clients can access 4 other routes. I am trying to implement this l ...