"Create a Vue element containing a trio of buttons each displaying a distinct numeral

I am currently dealing with a component that generates three items (boxes) each containing three buttons (created using v-for). The issue I am facing is that when I click on a button, all the numbers inside the buttons change simultaneously. I want to be able to change the number in each button individually upon clicking.

<template>
  <div>
    <div class="box" v-for="message in messages" v-bind:key="message">
      <p>{{ message }}</p>
      <button class="btn" v-on:click="updateCounter(message)">{{ getCounterValue(message) }}</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "childComponent",
  data: function () {
    return {
      messages: ["item 1", "item 2", "item 3"],
      counters: { "item 1": 0, "item 2": 0, "item 3": 0 },
    };
  },
  methods: {
    updateCounter(message) {
      this.counters[message]++;
    },
    getCounterValue(message) {
      return this.counters[message];
    },
  }
};
</script>

<template>
  <div class="container">
    <h2>I am the parent component</h2>
    <child-component />
  </div>
</template>

<script>
import childComponent from "./Hijo.vue";

export default {
  name: "fatherComponent",
  components: {
    childComponent,
  },
};
</script>

I have been working all day trying to solve this issue between the father and child components but I am struggling to find a solution.

Answer №1

The challenge lies in ensuring each button has its own unique counter value. To achieve this, the component must maintain a data structure that keeps track of individual counters for each message...

<template>
  <div>
    <div class="box" v-for="(counter, i) in counters" v-bind:key="i">
      <p>{{ counter.message }}</p>
      <button class="btn" v-on:click="counter.count++">{{ counter.count }}</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "childComponent",
  data: function () {
    return {
      messages: ["item 1", "item 2", "item 3"],
      counters: [],
    };
  },
  mounted () {
    this.counters = messages.map(message => ({ message, count: 0}));
    // this sets up counters as [ { message: "item 1" , count: 0 }, ... ]
  },
};
</script>

Answer №2

By ensuring each element has its own object with a unique counter, you can independently increment values without mutating the same counter on every button click.

Take a look at the code snippet below for an example:

<template>
  <div>
    <div class="box" v-for="value in values" v-bind:key="value.message">
      <p>{{ value.message }}</p>
      <button class="btn" v-on:click="value.counter++">
        {{ value.counter }}
      </button>
    </div>
  </div>
</template>

<script>
export default {
  name: "childComponent",
  data: function () {
    return {
      values: [
        { message: "item 1", counter: 0 },
        { message: "item 2", counter: 0 },
        { message: "item 3", counter: 0 },
      ],
    };
  },
};
</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

The Ajax PHP function only works on the initial call

The function below calls a PHP file that returns results in JSON format, which are assigned to JavaScript values. The PHP function has been thoroughly tested and works as expected. The results are stored in variables until the market variable is changed wi ...

Is it possible to verify the authenticity of published npm packages by utilizing hashes/checksums?

As I prepare to release an npm package on behalf of my organization, let's call it Organization A, I want our clients to have a means of verifying that the package they are using was indeed released by us. One method to accomplish this is by computing ...

Issue encountered while attempting to send a direct message to a user that has been mentioned

Attempting to create a reminder command in discord.js with two arguments: the message and the mentioned user to remind but encountering an error. Code snippet: client.on('message', (message) => { const { content, guild, channel, author } = m ...

I am having difficulty in crafting a sign-up form accurately

In my HTML file, I have a box that includes a sign-up form: <!-- sign up form --> <div id="cd-signup"> <form class="cd-form" action = "signup.php" > <?php echo "$error" ?> <p clas ...

Guide on securely presenting an HTTP-only cookie as a bearer token, without the use of Angular.JS

Can a JWT be securely stored as an HTTP-only cookie and also used as a bearer token without relying on Angular.JS? I believe this could be achievable, as Angular.JS offers similar features (although I'm not sure if they use an HTTP-only cookie to sto ...

Issues with Google maps are causing multiple maps to malfunction

After incorporating some jquery code to create multiple maps upon window load, I noticed a peculiar issue with the maps - they all display the same location despite having different latitudes and longitudes set. Upon inspecting the code responsible for cr ...

Managing Dependencies in Redux: Ensuring Proper Updates for Interconnected Resources

Let's say I have a redux state structure like this: { user: null, purchases: [], } The purchases are associated with a user, so whenever the user is updated, I also want to update the purchases (although there may be other times when purchases n ...

Utilizing `v-model` on a component that contains `<script setup>` in Nuxt can cause issues with the standard `<script>` tags

Working on a Nuxt3 project, I have implemented v-model on a component. Following the guidance from Vue documentation, here is how it should be done: In the parent component: <MyInput v-model="myData" placeholder="My placeholder" /&g ...

Unable to place value into an array following the invocation of a function in Angular 9

Within an array I established, I am encountering an undefined value when I use console.log. Take a look at my component.ts below: export class OrderExceptionReportComponent implements OnInit { public sessionData: ExceptionReportSessionData[] = []; n ...

Converting JSON data into an HTML table

I'm struggling to convert a JSON object into an HTML table, but I can't seem to nail the format. DESIRED TABLE FORMAT: Last Year This Year Future Years 45423 36721 873409 CURRENT TABLE FORMAT: Last Year 45423 This ...

Error: JSON parsing error due to unexpected token C at the beginning of the string

When using ajax and json formatting, I am encountering this message. In PHP, the code array("message" => "Success", "data" => $data) is displayed successfully. However, it is not able to callback to ajax. How can I resolve this issue without deleting ...

What is the reason behind obtaining a distinct outcome when logging the properties of an object compared to logging the object itself and checking its properties?

Currently, I am working on integrating socket-io with react redux and encountering a peculiar namespace problem. console.log(socket); console.log(socket.disconnected); console.log(socket.id); console.log(socket); The first log displays a comprehensive ob ...

Tips for extracting value from a chosen input field without relying on its unique identifier

I am working on a simple code to help guess notes by ear. The concept involves tabs with empty input fields where numbers need to be entered based on a specific melody for the guitar fretboard. One button reveals the first note, while another button checks ...

Unexpected website icon shows up in my Node.js project

As a newcomer to working with the backend of Node.js, I'm facing an issue while trying to integrate favicons into my project using RealFaviconGenerator. Despite following the instructions provided, the favicons are not showing up on either my developm ...

A step-by-step guide on implementing the bootstrap paginator library to paginate PHP echoed data

I'm currently working on a project that involves displaying data from a database in a table. To make the data paginated on the client side, I decided to use the bootstrap paginator library available at: Below is the code I'm using: In my header ...

Deselect an item from a three.js scene by clicking on it

In my three.js scene, I have multiple OBJ models, some already loaded in the scene and others added via a button click. If a user adds an object but later decides to remove it, I am seeking guidance on how to accomplish this effectively. My ideal solutio ...

Using regular expressions in JavaScript to extract the value following a colon, without including the colon itself

I've attempted using the tool, along with a similar stackoverflow question, but I'm still unable to solve or comprehend it. I hope someone here can shed some light on what I might be missing. I've provided as detailed and step-by-step examp ...

Forcing a property binding update in Angular 2

Take a look at this particular component import {Component} from 'angular2/core' @Component({ selector: 'my-app', providers: [], template: ` <div> <h3>Input with two decimals</h3> <input type ...

Prefering `window.jQuery` over the yarn version

I am currently in the process of transitioning to Vite 3 with Vite Ruby on Rails from Webpacker and Webpack. One major issue I have encountered is that my system functions as a CMS. Some of our long-standing clients have jQuery code embedded directly withi ...

When I implement the persist gate in Next.js with Redux, the flex direction automatically adjusts

I'm currently developing an app using next js and redux. An interesting issue has arisen - when I include PersistGate in my _app.js file, the flex direction mysteriously changes from row to column in index.js. There haven't been any modifications ...