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

Some mobile devices are experiencing issues with Android webview not executing javascript functions

Everything was running smoothly on my webview app on the HUAWEI RNE-L22 and iPhone. However, when I tried to run the app on the samsung SM-G530H, it failed to execute my JavaScript function. Surprisingly, the function worked fine on a normal phone browser. ...

"Exploring the seamless integration of easyXDM, AJAX, and En

In this new inquiry, I am facing a similar challenge as my previous query regarding loading a PHP file into a cross-domain page with dynamic element height. However, I am now exploring a different approach. Although I have managed to load my script into a ...

Which event occurs first for a4j:jsFunction, reRender or oncomplete?

After running a jsFunction, I want the javascript to execute once the re-rendering is completed. I assume that the "oncomplete" javascript function is triggered after the re-rendering process, but I'm not entirely certain. Any insights on this? Appre ...

Tips for effectively combining an array with jQuery.val

My goal is to have multiple form fields on a page, gather the input results into an array, and then store them in a database. This process was successful for me initially. However, when I introduced an autocomplete function which retrieves suggestions from ...

Filtering a collection using another collection in Backbone: tips and tricks

I am managing two distinct collections: Collection X includes element1, element2, element3, element4. Collection Y consists of element2, element3. For illustration purposes: var element1 = new models.ExModel({id: "1", name: "element1"}); var elemen ...

Background image not displaying in new tab after Chrome extension installation

I have been developing a Chrome extension that alters the background image of a new tab. However, I have encountered an issue where the background image doesn't change the first time the extension is loaded. This problem has also occurred very occasi ...

Assigning various variables with a single click of a button

I am attempting to perform multiple actions within a button click event using the Vuetify framework: <v-btn flat color="indigo darken-3" @click.stop="dialogDelete = true; deleteTemporaryId = offer.id">Delete</v-btn> However, it appears that ...

A tool designed to create a function that can fetch information from a JSON file

Currently, I am working on a function that accepts arguments and combines them to form a line for searching data in a JSON file. To accomplish this, I have initialized a variable for the readFileSync and then added the function's arguments to it in or ...

Creating a Node API that can patiently listen for external data

My current project involves building a server that fetches data from an external API and returns it to the endpoint localhost:3000/v1/api/. However, I'm facing a challenge where the data retrieval process takes approximately 2 seconds, leading to empt ...

Tips for checking the validity of PHP variable names, such as $as['abc'], within an HTML textbox

Can anyone assist me with validating a user input PHP variable name such as $as_cap['abc'] during insertion? I need to verify if the format of the variable name is correct or incorrect. Currently, I am using eregi("^[a-z0-9_.'-]{1,50}$") ...

Module for Npm that includes unique code for both proxy support and non-proxy support configurations

Is there a way to develop a javascript library (available as a module on npm) with multiple implementations based on the level of proxy support in the environment where it is executed (transpiled to)? From my understanding, babel may not easily transpile ...

Encountering the "potential null object" TypeScript issue when utilizing template ref data in Vue

Currently, I am trying to make modifications to the CSS rules of an <h1> element with a reference ref="header". However, I have encountered a TypeScript error that is preventing me from doing so. const header = ref<HTMLElement | null> ...

sending data from a callback to an express router

As I embark on learning node.js, I've encountered a challenging issue. In my passportAuth.js file, I create a user and have a callback to ensure the user is created successfully. The code snippet looks something like this: req.tmpPassport = {}; var ...

Adding local JavaScript to a Vue component is a great way to enhance its functionality

I am currently working on integrating a homepage concept (Home.vue) into my project. The design is based on a template that I purchased, which includes CSS, HTML files, and custom JavaScript. While most of the CSS has been successfully imported, I am havin ...

Tips for populating class attributes from an Angular model

Suppose there is a Class Vehicle with the following properties: public id: number; public modelId: number; public modelName: string; Now consider we have an object that looks like this {id: 1, modelId: 1, modelName: "4"} What is the best way to assign e ...

The function getElementbyId is not recognized

My JavaScript code is supposed to change the color of a button, but I'm running into an issue where it says that getting the button is not a function. Strangely enough, the same function (with the same capitalization and case) works perfectly just a f ...

Angular 2: Navigating through submenu items

I have a question about how to route submenu elements in Angular 2. The structure of my project is as follows: -app ---login ---registration ---mainApp (this is the main part of the app, with a static menu and links) -----subMenu1 (link to some con ...

I'm having trouble importing sqlite3 and knex-js into my Electron React application

Whenever I try to import sqlite3 to test my database connection, I encounter an error. Upon inspecting the development tools, I came across the following error message: Uncaught ReferenceError: require is not defined at Object.path (external "path ...

Images in CSS not copied to the output directory when using Webpack

Using Webpack to bundle various javascript and css files on a website includes bundling bootstrap.css and chosen.css as part of the bundles. To achieve this, there is a main.js file serving as an entry point for importing all necessary files. The process i ...

How to dynamically increase vote tallies with React.js

The voting system code below is functioning well, displaying results upon page load. However, I am facing an issue where each user's vote needs to be updated whenever the Get Vote Count button is clicked. In the backend, there is a PHP code snippet ...