Storing Data Property Value from an Item in Rendered List Using Vue: A Quick Guide

I'm currently working on implementing a follow button for list items in Vue. My approach involves extracting the value of a specific property from a list item and storing it in the data object. Then, I plan to utilize this value within a method to append it to an array in my database.

<div v-for="result in results" :key="result.symbol">
  {{ result.name }}
  <button @click="followStock(result.symbol)">+ Follow</button>
</div>

My challenge lies in figuring out how to pass the value of `result.symbol` into the button element in order to set the `symbol` value in the data object below.

<script>

export default {
  data() {
    return {
      results: [ // fetched from API
        {
          currency: "USD",
          exchangeShortName: "NYSE",
          name: "International Game Technology PLC",
          stockExchange: "NYSE",
          symbol: "IGT"
        },
        {...},
        ...
      ],
      symbol: "",
    };
  },
  
  methods: {
    followStock(symbol) {
      // add symbol to database array
    },
  },
};
</script>

I believe there could be a simpler solution that I may have overlooked since I am still new to Vue. Any alternative approach allowing me to send the value of `result.symbol` from any rendered result to my database would be greatly appreciated.

Answer №1

To pass the outcome as an argument to your function, you can simply do so.

<div v-for="outcome in outcomes" :key="outcome.event">
    {{ outcome.title }}
    <button @click="trackEvent(outcome)">+ track</button>
</div>

Within your function:

methods: {
    trackEvent(outcome) {
        // manipulate outcome
        console.log({outcome});
        let event = outcome.event;
    },
}

Note that I noticed you hadn't placed your trackEvent() within a methods object, but I have done so here for illustration purposes. https://v2.vuejs.org/v2/api/#methods

Answer №2

To implement as a function call directly, just write it like followStock(result.symbol). The vue compiler will automatically convert this into

function(event) {followStock(result.symbol)}
.

new Vue({
  el: '#app',
  data() {
    return {
      results: [
        {
          name: "International Game Technology PLC",
          symbol: "IGT"
        },
        {
          name: "A name",
          symbol: "A symbol"
        }
      ]
    };
  },
  methods: {
    followStock(symbol) {
      console.log(symbol)
    },
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
   <div v-for="result in results" :key="result.symbol">
      {{ result.name }}
      <button @click="followStock(result.symbol)">+follow</button>
   </div>
</div>

Answer №3

Just like Nazaire mentioned before, you have the ability to access the results from any child element when utilizing v-for.

(similar to a typical for-loop)

This feature is not restricted to just the element where you are using v-for.

<div v-for="result in results" :key="result.symbol">
    {{ result.name }}
    <button @click="followStock(result.symbol)">+follow</button>
</div>

followStock(symbol){
    // symbol can now be added to the db
}

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

Ar.js results in objects experiencing deformation or modification when manipulated

Recently, I started experimenting with Ar.js and encountered an issue where the objects displayed on the screen seemed distorted. To illustrate this problem, let me share a basic A-Frame example featuring a perfectly round sphere: <!DOCTYPE> <html ...

Inject object into data attribute

I currently have data stored in a specific attribute like this: <div data-id=""> Within my markdown file, I also have a frontmatter variable like this: id: rick My goal is to pass that variable into the data-id attribute, which only accep ...

What causes images to be omitted from a PDF file when using mywindow.print()?

Here is the scenario I am dealing with: On a particular webpage, there is a print button. The page contains various information, including receipts. When the user clicks on "print", I want only the receipts to be printed: Below you can find the code for ...

Redirecting with React Router outside of a route component

I am using React Router in my application to manage the routing functionalities. However, I have encountered an issue where I need to redirect the user from the Header component, which is not nested inside the Router component. As a result, I am unable t ...

Generating a single JSON record in React Native

Need help displaying a single JSON record from an API request on the screen. const [user, setUser] = useState(); const getUserData = async () => { // {headers: {Authorization: "Basic " + base64.encode(username + ":" + passwor ...

The data provided was deemed incorrect. Modifying the function to include file uploads in Laravel 8 and Vue 2

I've been attempting to create an update function that includes file upload capability. Here is what I have experimented with so far: <b-form @submit.prevent="update" enctype="multipart/form-data"> . . . . <b-form-f ...

Encountering issues with importing Vue library

I have recently set up a Vue application using the Vue CLI. Everything seems to be working smoothly except for an import issue that I encountered. The following import statement works without any errors: import Vuex from 'vuex'; However, this ...

What is the best way to capitalize the first letter of a string in JavaScript?

Is there a way to capitalize only the first letter of a string if it's a letter, without changing the case of any other letters? For example: "this is a test" → "This is a test" "the Eiffel Tower" → "The Eiffel ...

Creating a masterpiece on the final piece of paper

As someone who is new to programming with JavaScript and canvas, I have a function called drawLines(canvasIndex, startPosition) that is used to draw lines on a canvas. The function takes in two arguments: canvasIndex, which represents the canvas being draw ...

A guide on loading static JS files in the correct order using VueJS 2

I've come across an issue with my HTML theme that uses jQuery and a minified custom JS plugin. The application requires jQuery to be loaded before the custom plugin, but unfortunately I am unable to edit the minified plugin itself. mounted() { let ...

Evaluate the functionality of an Angular controller method that interacts with the Document Object Model (

We currently have an AngularJS controller that contains the following function: $scope.testMe = function() { return $('#test'); } So, how can we effectively test this function? We attempted a Karma test as shown below: describe(' ...

What is the best way to pass multiple parameters along with the context to a URL in Vuex?

Link to StackBlitz I am currently working on how to send multiple action parameters with context to a URL. I have been encountering a 400 error in my attempts. The selectedPoint and departurePoint are coming from child components and stored as variables i ...

Puppeteer's flawed performance leads to the generation of low-quality

Currently, I am utilizing puppeteer to generate a PDF from my static local HTML file. However, the resulting PDF is turning out to be corrupted. When attempting to open the file using Adobe Reader, an error message pops up stating 'Bad file handle&apo ...

Retrieving information in Ionic

Having trouble fetching data from a server in my first ionic application. I keep getting an error that says "Cannot read Property" while trying to attach my code snippet. Here is what my code looks like: import { Component } from '@angular/core' ...

Adding and Removing Attributes from Elements in AngularJS: A Step-by-Step Guide

<input name="name" type="text" ng-model="numbers" mandatory> Is there a way to dynamically remove and add the "mandatory" class in Angular JS? Please note that "mandatory" is a custom class that I have implemented. Thank you. ...

Utilize OpenLayer3 to showcase Markers and Popups on your map

I am currently exploring how to show markers/popups on an osm map using openlayers3. While I have come across some examples on the ol3 webpage, I'm interested in finding more examples for coding markers/popups with javascript or jquery, similar to som ...

Executing a callback function when a window confirmation is triggered during the onbeforeunload event

Currently, I need to implement a feature where a confirmation window pops up when the user tries to close the page. The code snippet for this functionality is included below: window.onbeforeunload=function(){ if(...) { return "Are you sure you want to ...

React and Express are incompatible due to the error message "TypeError: undefined is not a function

I am attempting to display the data from this array on my website using react and express: [{"LocationName":"LIBERTY DOGS","Address":"105 Greenwood Ave N, Seattle WA","Available":"Y"},{"LocationName":"FREEDOM DOGS","Address":"105 Greenwood Ave N, Seattle ...

positioning a text input in the center instead of at the top of the page

Hello everyone, I am just starting out with HTML and I have a question. How can I make the Username: <input type="text" name="Username" style="- margin-top: 200px;"> appear in the center of the page instead of at the top? I've tried changing the ...

Maintaining data after page reload in Angular

angular.module('eventTracker', []) .controller('MainCtrl', ['$scope', 'Event', function($scope, Event){ $scope.eventData = {} $scope.onSubmit = function(){ Event.Add($scope.eventData) $scope. ...