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

Exploring the properties of a file directory

As I try to access the d attribute of a path that was generated using Javascript, the output of printing the path element appears as follows: path class=​"coastline" d="M641.2565741281438,207.45837080935186L640.7046722156485,207.0278378856494L640.698 ...

Preventing Vue.js from triggering watch on initial load

I need to implement a feature where a button is initially disabled and only becomes enabled when the input value is changed. To achieve this, I am using a boolean flag that is set to true by default and turns false only when the input changes. The v-model ...

Adding a modified (id) content inline template element to another element: A step-by-step guide

In the given scenario, I am looking to achieve a function where each time the add button is clicked, the content within the template div should be appended to the element with the landingzone class. Additionally, it is important that the NEWID changes for ...

Limiting the style of an input element

How can I mask the input field within an <input type="text" /> tag to restrict the user to a specific format of [].[], with any number of characters allowed between the brackets? For example: "[Analysis].[Analysis]" or another instance: "[Analysi ...

JavaScript library designed for efficient asynchronous communication with servers

Looking for a lightweight JS library to handle AJAX cleanly and simplify basic DOM selections on our website (www.rosasecta.com). Currently, we're manually coding a lot of Ajax functionality which is not only ugly but also difficult to manage. We&apos ...

Bidirectional data binding in Vue.js allows for seamless communication between different components

I need help troubleshooting this pseudo code that isn't working as expected: Vue.component('child', { props: [], template: '<div><input v-model="text"></div>', data: function() { return {child- ...

Tips for modifying the value of a JSON object using Javascript or Jquery

I am looking to retrieve the value of a specific key, potentially accessing nested values as well. For example, changing the value of "key1" to "value100" or "key11" to "value111. { "key1": "value1", "key2": "value2", ...

Trouble confirming the password field with regular expressions in angular.js

I'm trying to validate my password field with specific special characters requirements. The field must contain at least one number, upper case letter, lower case letter, and an underscore, all of which are mandatory. I have attempted to achieve this u ...

The misleading A*(A-star) algorithm inaccurately produces faulty routes and ultimately collapses

I am currently working on implementing the A*(A-star) algorithm in react.js, but I am facing a problem. Whenever the startNode (green) or destinationNode (blue) have more than one neighbour or if there is a cycle in the graph, my program crashes. There see ...

Encountering an issue of THREE.EventDispatcher being undefined while trying to create a THREE.OrbitControls instance using THREE.js, THREE.OrbitControls, and TypeScript

Attempting to delve into typescript alongside three.js, I've encountered a perplexing error that has me stumped. The root of the issue lies within the init function where I initialize a new THREE.OrbitControls controller. Utilizing the setup provided ...

Transform JSON time data from Coordinated Universal Time (UTC) to Indian Standard

Hello, I consider myself an amateur in the world of online javascript learning. Currently, I have come across a challenge that has left me stuck. I am working with a JSON time data provided in UTC format (e.g. 16:00:00Z) and my goal is to convert it to IS ...

Is there a way to retrieve data from a servlet using jQuery without having to make a request?

Struggling with a specific scenario: Imagine having 2 jsp pages: page1 and page2 Upon clicking a button in page2, the button sends an ID to page1. Based on that ID, information is retrieved from the database and sent to a JavaScript file related to page ...

Create a navigation link in Vue-bootstrap that directs to an 'external program'

After deciding to use vue-bootstrap instead of just bootstrap for its additional features like tabs, I made the choice to rewrite the navigation using it as well. However, I encountered an issue where the links in the navigation menu are pointing to the co ...

Utilize the power of dual API integration in a single request (multi-scope capability)

While there may not be a definitive answer to this question, I want to ensure that my situation cannot be resolved in any way. The crux of my application (and consequently the issue) is that each user possesses their own unique database and does not have ...

Sort through a list of objects by certain properties

I'm currently dealing with two arrays: one contains displayed columns and the other contains objects retrieved from a database, with more attributes than the displayed columns. displayedColumns = ['CompanyName','Ticker', 'Id& ...

Retrieving fresh CSS data from earlier animated elements within a Greensock timeline

In my code, I am using a TimelineLite() to perform a series of sequential tweens with .to(). What I want to achieve is accessing the output value from one of the early tweens in order to use it for constructing later tweens. Is there any way to retrieve t ...

Is there a way to create a navigation menu that highlights as we scroll down the page?

Check out this example of what I am looking for. https://i.stack.imgur.com/fdzvZ.png If you scroll, you will notice that the left menu highlights. Sub-menus will extend when the corresponding menu is highlighted and collapse when other menus are highlig ...

When using Javascript template literals, they function properly when assigned to a variable, but they do not work when included in a JSON

Trying to get a grasp of Javascript. Let's say I have a variable declared with template literals: var templateObject = `Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}.` This functions correctly as sh ...

Please eliminate the forward slash (/) from the end of my route

Could anyone help me figure out how to remove the trailing slash at the end of routes in Nuxtjs? I attempted using the @nuxtjs redirect-module and setting the trailingSlash property to false, but instead of removing the slash, it adds multiple slashes at ...

Tips for obtaining a cropped image as form data in React after the cropping process

import React, { PureComponent } from 'react'; import ReactCrop from 'react-image-crop'; import 'react-image-crop/dist/ReactCrop.css'; class CoachDashboard extends PureComponent { state = { src: null, crop: { u ...