What is the best way to access the items generated within a v-for loop?

Currently running a little experiment as I dive into VueJS. My main query revolves around how to access the marker object generated through the v-for loop.

<gmap-marker
      :key="index"
      v-for="(m, index) in markers"
      :icon="m.icon"
      :position="m.position"
      :clickable="true"
      :draggable="true"
      @click="center=m.position"
    ></gmap-marker>

I am considering assigning an ID to each of the created markers and then collecting them within an object literal where the ID serves as the key and the marker object as the value. This approach would allow me to reference individual markers using their respective IDs.

Do you think this is the appropriate method to pursue in VueJs?

Many thanks!

Answer №1

To utilize references, you can use the following code:

  <gmap-marker
      :key="index"
      v-for="(m, index) in markers"
      :icon="m.icon"
      :position="m.position"
      :clickable="true"
      :draggable="true"
      @click="center=m.position"
      ref="marker"
    ></gmap-marker> <!-- notice the addition of ref="marker" attribute -->

Later on, you can reference it like this:

this.$refs.marker[index]

The value of index should be an integer. The [index] is necessary when using ref within a v-for loop.

Here is a quick demo:

Vue.component('gmap-marker', {
  props: ['icon'],
  template: '<div>marker {{ icon }}</div>'
})

new Vue({
  el: '#app',
  data: {
    markers: [{
      icon: 'aaa'
    }, {
      icon: 'bbb'
    }, {
      icon: 'ccc'
    }]
  },
  methods: {
    printMarkers() {
      console.log(this.$refs.marker.length);
    }
  }
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>

<div id="app">
  <gmap-marker
      :key="index"
      v-for="(m, index) in markers"
      :icon="m.icon"
      :position="m.position"
      :clickable="true"
      :draggable="true"
      @click="center=m.position"
      ref="marker"
  ></gmap-marker>
  <hr>
  <button @click="printMarkers">Print Marker Refs at Console</button>
</div>

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

Error message: "jQuery Ajax CORS request returning undefined value"

I am delving into the world of cross-domain Ajax requests for the first time by interacting with an API. Utilizing jQuery, I aim to extract specific elements from the response and display them on the webpage. Here is the code snippet for the request: $.a ...

Executing a Knex RAW MySQL query to insert new records into a database table

As someone new to working with MySQL, I have previously used PSQL in a similar manner. However, the following code is generating an error. return await db .raw( `INSERT INTO users(firstName, lastName, email, ...

The continual appearance of "No file found" persists when utilizing the $redirectRoute

My goal is to make one of the links on my website lead to another page within the site. Below is one of the two links found on my index.html page: <html ng-app="myApp"> . . . <body> <h1>My Home Page</h1> ...

Webpage created from scratch encounters technical difficulties on mobile device browser

My website seems to be getting stuck at the beginning of a section, particularly on mobile browsers. You can check out the website here <section class="home-slider owl-carousel"> <div class="slider-item" style="background-image: url(images/bg ...

Hover over to disable inline styling and restore default appearance

There are some unique elements (.worker) with inline styles that are dynamically generated through Perl. I want to change the background when hovering over them and then revert back to the original Perl-generated style. The only way to override the inline ...

Why is this loop in jQuery executing twice?

$(document).bind("ready", function(){ // Looping through each "construct" tag $('construct').each( alert('running'); function () { // Extracting data var jC2_events = $(this).html().spl ...

Having difficulty assigning an argument to an HTTP get request in AngularJS

I am new to working with AngularJS and I am attempting to pass an integer argument to an HTTP GET request in my controller. Here is a snippet of my code: (function() { angular .module('myApp.directory', []) .factory('Ne ...

The navigation bar scrolling based on mouse position lacks smoothness and could use some enhancement

I'm currently working on adjusting the navigation bar based on the mouse position. It seems to be functioning, but I'm facing an issue with smoothing out the animation. When I stop moving the mouse to a certain point, there is a delay i ...

Ways to enhance the data for my YouTube video uploads version 3

Currently facing an issue where Google has restricted my daily queries to 10,000. I am in search of a solution to adjust my chunksize either up or down. Uncertain about the exact amount to increase or decrease to limit the number of queries per upload, her ...

What could be causing the PHP output to not be successfully inserted into the Vue data array?

While I am in the process of learning the basics of Vue.js, a question has arisen: when I fetch data using PHP, why is it not possible to insert it into the Vue object data array? data: { message: "vue?", homeView: true, brandV ...

Efficiently utilizing state in Redux

I encountered an issue with the following react redux code: The combined reducer looks like this const AllReducers = combineReducers({ foolow: follow_Reducer, vacations: vacations_Reducer, register: register_Reducer, ...

Setting default values for Vue prop of type "Object"

When setting default values for objects or arrays in Vue components, it is recommended to use a factory function (source). For example: foobar: { type: Object, default() { return {} } } // OR foobar: { type: Object, default: () => ({}) ...

"The event triggers the function with an incorrect parameter, leading to the execution of the function with

Currently, I am working with a map and a corresponding table. The table displays various communities, each of which has a polygon displayed on the map. My goal is to have the polygons highlighted on the map when hovering over a specific element in the tabl ...

Can default query parameters be predefined for a resource in AngularJS?

When working with a simple resource like the one defined below, it is possible to utilize the Receipt.query() method to retrieve a collection from the server. In addition, by calling Receipt.query({freightBill: 123}), a query parameter such as freightBill ...

Creating a dynamic form field using JavaScript

I'm struggling with a JavaScript issue that requires some assistance. I have a form sending an exact number of inputs to be filled to a PHP file, and now I want to create a preview using jQuery or JavaScript. The challenge lies in dynamically capturin ...

What exactly does a module's scope entail in browsers and Node.js environments?

Can someone clarify the scope of a module in different environments like browsers and Node? I'm particularly interested in whether a module-level variable is initialized once for the entire application or multiple times. Is each import creating a new ...

Struggling to display AJAX GET results on my webpage, although they are visible in the Google Element Inspector

I'm working on a basic invoice page where I need to populate a dropdown box from my MySQL database. The issue I'm facing is that when I select an item, the description box doesn't get prepopulated as expected. I've checked in the networ ...

Is there a way to alter the appearance of an HTML element without an ID using a JavaScript function?

I have a specific goal in mind, but I'm struggling to articulate it concisely. Despite conducting extensive research, none of the suggested solutions seem applicable in my case. Objective: I aim to change the background color of a div based on the da ...

Restrict magnification in THREE.js mousewheel interaction

Seeking advice on limiting zoom in and out of a model in three.js. I have explored trackball controls, but couldn't find a way to restrict zooming. I also experimented with orbit controls, but encountered issues when combined with trackball controls r ...

Animating text with a shake effect using JQuery

I am attempting to create a shake effect on my text input field when validation fails. While I have achieved the shake effect, I am unsure how to customize the default values for direction, distance, and times. Additionally, I believe there is an error i ...