The process of retrieving an item from an HTML node using Vue.js

My scenario involves a Vue app with the following data:

data: function() {
    return {
        items: [
            {id: 1, text: 'one', other_data: {}},
            {id: 2, text: 'two', other_data: {}},
            {id: 3, text: 'three', other_data: {}}
        ]
    }
}

The template is structured as follows:

<div v-for="item in items" id="my_items">
    <span>{{ item.text }}</span>
</div>

I am looking to access a specific item by using external JavaScript code, like this example:

let item_node = document.getElementById('my_items').children[1]; // Retrieve the 2nd child node of #my_items
item_node.__vuedata__ // This should represent the second item from the Vue data. {id: 2, text: 'two'...

Is there a way to achieve this functionality?

Answer №1

Vue suggests using the ref attribute instead of IDs and classes for DOM references. By utilizing ref with the v-for directive, child elements can now be referenced as an array of the ref. This means that each span will be accessed as hello[0] - hello[n]. The mounted code snippet displays the item.text for the first child element since it starts at index 0.

I've included a click listener that passes the value of item to a method every time you click on the element. This allows you to extract all values and perform any desired manipulations. I hope this meets your requirements.

<template>
  <div id="app">
    <div v-for="item in items" :key="item.id" ref='hello' @click="logItem(item)">
      <span>{{ item.text }}</span>
    </div>
  </div>

</template>

<script>

export default {
  name: "App",
  data: function() {
    return {
        items: [
            {id: 1, text: 'one', other_data: {}},
            {id: 2, text: 'two', other_data: {}},
            {id: 3, text: 'three', other_data: {}}
        ]
    }
  },
  methods: {
    logItem: (item) => console.log(item)
  },
  mounted: function() {
    console.log(this.$refs.hello[0].innerText)
  }
};
</script>

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

When using VueJs to loop through a list of options in a dropdown menu, the value of the selected option is showing as undefined instead of

Consider the code snippet below, designed to display a form stepper. In this example, I have simplified it to show only one step: <form-wizard :formdata="this.form_data"> <form-tab stepindex="1" title="Title of Tab" :selected="true"> ...

Utilizing Multiple Checkboxes for Precision Search Refinement

Big thanks to Khalid Ali for the support provided up until now. I am currently working with an array of songs that each have descriptions, keywords, etc. I have a set of checkboxes that I want to use to refine a search. Essentially, if someone selects the ...

Is there a way to establish the starting content/value for this tinymce editor?

I have integrated tinymce editor from this repository into my application: https://github.com/dyonir/vue-tinymce-editor. My goal is to pre-populate the editor with content upon initialization. Although I attempted using v-model, it did not work as expect ...

Adjusting the character limit for my textarea input

Here is the styling for my textarea: textarea { min-width: 120px; min-height: 90px; padding: 8px 10px; background: #FFF; border: 1px solid #E0E0E0; border-radius: 2px; outline: none; padding: 8px 10px; box-shadow: inset ...

Organizing with dynamic attributes within angularJS

I have been working on creating a spreadsheet using Angular, and I have managed to implement most of the basic features. However, I am facing a challenge with sorting data by a single column within my current data structure. Here is the link to the Plnkr ...

Improving communication between Components in ReactJS

I am attempting to update the state from one component to another component. I wish for the state total on header.jsx to be updated when I click on the add to cart button on product.jsx Below is my code: index.jsx // Code for index.jsx goes here head ...

Do global variables in a node.js server apply across the entire server or exclusively to individual sessions or users?

I have a question that may seem basic, so I apologize in advance - are global variables in node.js applicable server-wide or is their scope limited to the session or user? For example, if I create a global boolean variable in a routes.js file to track whet ...

Position an element with absolute positioning to the right edge of a relative element

I have a situation where I need to align the end of a position absolute element with the end of a relative element, but the relative element's width is not fixed and may vary based on content. https://i.sstatic.net/L2sLP.jpg This scenario arises as ...

The callback function of jQuery getJSON would sometimes not be triggered

I've been struggling with this issue for hours now, and I can't seem to figure out why. Oddly enough, q seems to be functioning correctly. The URL returns a valid JSON response, displaying objects and arrays in the JSON tab under the Net-tab ...

Typescript double-sided dictionary: a comprehensive guide

Looking for a dual-sided dictionary implementation in TypeScript that allows you to retrieve values using keys and vice versa. An initial approach could be storing both items as keys: dict = {"key": "value", "value": "key"} But I am curious if there are ...

I am facing difficulty showing JSON data using Vue.js

I'm having trouble using v-for to display the products array from a JSON data. The attempt to showcase the product data from the array isn't yielding results as expected. Vue.js <div class="box" v-for="product in products" ...

What is the process for sorting Google Map markers with AngularJS?

.controller('MapCtrl', ['$scope', '$http', '$location', '$window', '$filter', '$ionicLoading', '$compile','$timeout','$ionicPopup', function ...

Encountering Issues with Importing vue-router in Vue.js 3 - What Could be the Problem?

Here are the files I am working with: router.js import VueRouter from 'vue-router' export const router = VueRouter({ routes: [ { ... } ] }) main.js import { createApp } from 'vue' import App from './App.vue ...

Flask API returning error: Missing 'Access-Control-Allow-Origin' header for POST requests

I've been diving into my first API project and so far have relied on Google for assistance. However, I've hit a roadblock with the following issue: While my POST requests are successful in Postman, using a form in my HTML to make a POST request ...

Implementing promises in Node JS Express

I am new to promises and trying to understand how they function. Here are my initial questions: When a request is handled in a route function, does it wait for all promises? Does using a promise or callback create a new scope where execution continues ...

Trouble encountered in PHP: Generating a file from POST data and initiating download prompt for the user not functioning as intended

On my webpage, users fill out forms and input fields, which are then sent to a PHP page via Ajax and $_POST. The PHP file successfully writes the output to a txt file. However, I'm facing an issue trying to prompt the user to download the file on the ...

Dealing with Database Timeout in Express JS

I have been trying to extract SQL query execution into a separate file to prevent code repetition, but I am facing timeout issues during execution. var mysql = require('mysql'); const connectionData = { host: 'localhost', user: ...

Error: The function loadJSON has not been declared

Currently utilizing the Atom text editor, I have successfully installed node.js along with npm install -g json. The installation process was smooth and the version information displayed correctly in the command prompt window. Running a server using nodemon ...

If there is an error in retrieving data from the PHP file using `$.getJSON

Currently, I am integrating JSON into my login script and have included the following code snippet: $.getJSON("link to PHP where to get the JSON data from", function (data) { // THE CODE TO BE EXECUTED }); My question is, what is the most efficient way t ...

Using JavaScript with Selenium, you can easily clear the input field and send

Here is a question input field. When clicked on, the h3 element with the name will disappear and the input tag will appear for entry of a new name. <td style="width:92%;"> <h3 id="question_tex ...