Generate live references to interact with elements

I am facing a challenge in my vue app where I need to access a specific element, but there are multiple duplicate elements generated through a component. The issue is that the ref attribute only seems to work on the first component. How can I target a particular element among these duplicates?

The key idea here is that the component below receives a prop called "type", which could potentially serve as a unique identifier for the ref.

Is there a way to either (a) create a variable dynamically based on the props.type value, or (b) reference a specific div within multiple instances of components?

In the Main.vue file, Component.vue is rendered multiple times. However, if the ref within the component has a static name, it appears to work only on the first instance and not on subsequent ones.

The ultimate goal is to be able to scroll to the clicked div within one of these multiple components.

Main.vue

<div v-for="(m, i) in array" 
 :key="i" >
  <Component
    :type="m"
  />
</div>   

Component.vue

<template>
  <div :ref="type">text</div>
</template>
<script>
  import {
    onBeforeUpdate,
    reactive,
    ref,
  } from 'vue';
  props: {type: {type: String}}
  export default {
    setup() {
      const div = ref(null);

    onMounted(() => {
       div.value = props.type;
    });

return {
  div,
 };
},
};
</script>

Answer №1

To utilize Refs inside v-for, you should use an array or function as per the Vue.js documentation.
In the child component, make sure to use defineExpose() to bind to the necessary element through the Component Reference.

Here is a straightforward example:

/* App.vue */
<script setup>
import { ref } from 'vue';
import Component from './Component.vue';

const divs = ref([]);

const cliskedDivText = ref('');

const click = (index) => {
  /* divs.value[index].div - is ref HTMLElement */
  cliskedDivText.value = divs.value[index].div.innerText 
}

const array = ['type_1', 'type_2'];

</script>

<template>
  <div
    v-for="(type, index) in array" 
    :key="index"
  >
    <Component
      :type="type"
      :ref="el => divs[index] = el"
    />
  </div> 
  <br>
  <div class="btns">
    <button
      v-for="(type, index) in array"
      @click="click(index)"
    >
      click {{ type }}
    </button>
  </div>
  <br>
  {{ cliskedDivText ? `Click to DIV with text ${cliskedDivText}` : '' }}
</template>
/* Component.vue */
<script setup>
import { ref } from 'vue';

defineProps({
  type: String,
})

const div = ref();
defineExpose({ div });
</script>

<template>
  <div ref="div">Component with {{ type }}</div>
</template>

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

Using NextJS getServerSideProps to Transfer Data to Page Component

Having trouble with my JavaScript/NextJS code, and not being an expert in these technologies. I'm using the method export const getServerSideProps: GetServerSideProps = async () => {} to fetch data from an integrated API within NextJS. The code mig ...

Is ngSwitch in Angular causing the label element to disappear?

I am using AngularJS to generate form elements dynamically based on an array containing form details such as input type and value. For example, here is the code snippet I have for creating a text input field: <div ng-repeat="input in input_array"> ...

Exploring ways to customize the input color of Material UI TextField when it is disabled [Version: 5.0.8]

I am having trouble changing the border color and text color when an input is disabled. I have tried multiple variations, as seen below: const textFieldStyle = { '& label': { color: darkMode?'#1976d2':'', } ...

Troubleshooting Cross-Origin Resource Sharing Problem in Vue.js Single Page Application and Node.js API

My Node.js Express app is set up with the cors npm package installed. Additionally, there is basic authentication enabled on the nginx server hosting my Node.js app (authentication requires an 'Authorization' key in the headers of each request). ...

Encountered difficulties while attempting to set up React.js

Why am I encountering difficulties installing React? I managed to create a node module file, but it is being automatically deleted. I ran the command npx create-react-app my-app. Below is a screenshot. Aborting installation. npm install --no-audit --save ...

Incorporate a customizable month option within a flexible calendar design

I'm working on creating a calendar that adjusts to different screen sizes for my website. The script I've implemented is as follows: <script type="text/javascript"> $(document).ready(function () { $(".responsive-calendar").responsiv ...

Observe the present time in a specific nation

Is there an authorized method to obtain and showcase the current accurate GMT time instead of relying on the easily manipulable local time on a computer? I am looking for a reliable way to acquire the current time in hours/minutes, so I can make calculati ...

Initiating a AJAX upload upon selection of a specific option from a select menu

Recently, I have been exploring ways to enhance my layout page by implementing an option for users to upload new logos on the spot. Currently, users are able to choose their desired image through a drop-down selection feature. I am interested in adding a f ...

Unable to retrieve content using the query.ID in Next.js

I'm trying to figure out what is causing the issue in this code, but I can't seem to resolve it. My goal is to use the query.id inside getInitialProps to fetch some content. The fetching process works fine, but when an error occurs, I receive thi ...

An HTML attribute with a blank value will not display the equals sign operator

jQuery can be used like this: $select.append('<option value="">All</option>'); This code appears to insert the element in HTML as follows: <option value>All</option> However, what is intended is to append the elemen ...

Is there a way to horizontally navigate a pallet using Next and Prev buttons?

As someone new to development, I am looking for a way to scroll my question pallet up and down based on the question number when I click next and previous buttons. In my pallet div, there are over 200 questions which are dynamically generated. However, th ...

Converting Dynamo DB stream data into Json format

I need to convert the DDB stream message into a standard JSON format. To achieve this, I am using unmarshalleddata = aws.DynamoDB.Converter.unmarshall(result.NewImage); where result.NewImage is { carrier: { S: 'SPRING' }, partnerTransacti ...

Ways to showcase a JavaScript popup on an Android WebView

Can a JavaScript popup window be opened on an Android web viewer that is coded similarly to this example from Google? If so, how can this be accomplished without closing the original background page and ensuring it resembles a popup as shown in the picture ...

React Component is not functioning with the timer running

I am currently developing a basic timer app using React. Here is the code snippet I have so far: import React from "react" const timer = (props) => { let time = 25; let processStatus = props.timerProcessStatus; // set to true if(processSta ...

The issue of req.file being consistently undefined in Node.js multer

I am having issues trying to upload a file using multer because the req.file is always undefined and the destination folder remains empty: Server: var express = require('express'); var multer = require('multer') var app = express(); ...

Creating a JavaScript file to incorporate into an HTML document

I stumbled upon this code snippet here This code allows me to fetch data from a php file and insert it into a div using jQuery. While the tutorial works perfectly, I'm planning to use this for about 9-10 different links and thought of consolidating a ...

What is the best way to incorporate a range of details into a div using only jQuery, all while avoiding the use of data-

I'm struggling to find a concise way to explain this, so please bear with me. The information I'm sharing here is all just for example purposes and may sound strange. I have been working on creating a character select page where clicking on a cha ...

Error: The getter callback for the component `RNCSafeAreaProvider` must be a function, but it is currently undefined

After attempting to update my React Native app's dependencies using npm update, chaos ensued. To rectify the situation, I reverted back to the previous package-lock.json, deleted the node_modules folder, and re-ran npm i. Surprisingly, instead of res ...

Ensure that clicking on an element closes any currently visible elements before opening a new element

Take a look at my code snippet below. I am working on creating multiple clickable divs that reveal different content when clicked. However, the issue I am facing is that currently, both content blocks can be displayed simultaneously. My goal is to have onl ...

What could be causing the lack of animation in W3schools icons?

I've followed the steps provided and even attempted to copy and paste them. However, I'm experiencing an issue where the animation doesn't fully execute. Instead of the bars turning into an X shape, they reset halfway through the animation. ...