Using VueJs to create custom Like and Unlike buttons with Vfor loop

How can I make the buttons increase separately? I've tried similar solutions, but they currently increase the number of likes and dislikes together at the same time. Additionally, I am receiving this message in the console:

vue@next:1250 [Vue warn]: Property "counter" was accessed during render but is not defined on instance. at

<div class="container">
      <div class="comment--like--dislike--app">
        <div
          v-for="(comment, index) in comments" :key="index"
          class="card mb-10 comment--item"
        >
          <p>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint
            deserunt, tempore accusamus iusto nobis dolore ratione itaque
            perferendis delectus? Nostrum corporis, quod voluptates quis
            consequuntur eveniet beatae dolor aperiam ad.
          </p>
          <div class="action--button--container text-right mt-10">
            <button v-on:click="increment(index)" v-bind:id="comments.id" class="btn-sm btn-success">
              Like ({{comments.counter}})
            </button>
            <button  v-on:click="increment(index)" v-bind:id="comments.id"  class="btn-sm btn-danger">
              Dislike ({{comments.counter}})
            </button>
          </div>
        </div>

This is the current Vue code being used:

const app = Vue.createApp({
        data() {
          return {
            comments: [{
              id: 1,
              counter:0
            },
            {
              id: 2,
              counter:0
            },
          ],
          };
        },
        methods: {
          increment: function(index) {
            this.comments[index].counter++;
          },
        },
      }).mount(".container");

Answer №1

It appears that the issue lies in using comments.counter instead of comment.counter (which refers to the comment at the current index in the array comments).

To rectify this, modify your markup as follows:


<div class="container">
    <div class="comment--like--dislike--app">
        <div v-for="(comment, index) in comments" :key="index" class="card mb-10 comment--item">
            <p>
                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint
                deserunt, tempore accusamus iusto nobis dolore ratione itaque
                perferendis delectus? Nostrum corporis, quod voluptates quis
                consequuntur eveniet beatae dolor aperiam ad.
            </p>
            <div class="action--button--container text-right mt-10">
                <button v-on:click="increment(index)" v-bind:id="comment.id" class="btn-sm btn-success">
                    Like ({{comment.counter}})
                </button>
                <button v-on:click="increment(index)" v-bind:id="comment.id" class="btn-sm btn-danger">
                    Dislike ({{comment.counter}})
                </button>
            </div>
        </div>
    </div>
</div>

Furthermore, as pointed out by ashwin bande in the comments section, there is also a logic inconsistency. Both like and dislike buttons are utilizing increment(index).

The desired outcome can be achieved with the following code snippet:

const app = Vue.createApp({
  data() {
    return {
      comments: [{
          id: 1,
          counter: {
            likes: 0,
            dislikes: 0
          }
        },
        {
          id: 2,
          counter: {
            likes: 0,
            dislikes: 0
          }
        },
      ],
    };
  },
  methods: {
    increment(index) {
      this.comments[index].counter.likes++;
    },
    decrement(index) {
      this.comments[index].counter.dislikes++;
    },
  },
}).mount(".container");
<script src="https://unpkg.com/vue@next"></script>

<div class="container">
  <div class="comment--like--dislike--app">
    <div
      v-for="(comment, index) in comments"
      :key="index"
      class="card mb-10 comment--item"
    >
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint 
        deserunt, tempore accusamus iusto nobis dolore ratione itaque 
        perferendis delectus? Nostrum corporis, quod voluptates quis 
        consequuntur eveniet beatae dolor aperiam ad.
      </p>
      <div class="action--button--container text-right mt-10">
        <button
          @click="increment(index)" 
          :id="comment.id"
          class="btn-sm btn-success"
        >
          Like ({{comment.counter.likes}})
        </button>
        
        <button
          @click="decrement(index)"
          :id="comment.id"
          class="btn-sm btn-danger"
        >
          Dislike ({{comment.counter.dislikes}})
        </button>
      </div>
    </div>
  </div>
</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

Having trouble retrieving JSON data using http.get method, as the status returned is -1

I'm a beginner in AngularJS. I'm attempting to retrieve JSON data in my code using $http.get, but it's throwing an error and the status is showing as -1. What could be causing this issue? RecordApp.factory('recordaccess', [' ...

Axios mistakenly sending DELETE requests before GET requests

I'm currently developing a Vue.js project that is connected to a Lumen API and everything is functioning smoothly. Within this project, I have implemented a list of students ('Etudiants') that allows users to select and delete a student by ...

When I avoid using a string ref, I encounter the error message "Error: Function components are not allowed to have string refs"

Recently, I created a new component const Projects = () => { const state ={ activeItemID: 1 } const CarouselRef = useRef(null); const NextSlide = () => { CarouselRef.current.style = "opacity: 0"; } return( <Co ...

The AngularJS framework is failing to disable the autocomplete feature for the input field with a password type

I have attempted to disable auto-complete for the password input, but it doesn't seem to be working. Below is a sample of my code: <form name="testfrm" ng-submit="test(testfrm)" autocomplete="off"> <input type="password" id="passwor ...

Can a value of a variable be "stored" in NodeJS?

I am working on a website that allows clients to make their site go live by setting var live = true;. Once this variable is set, certain webpages will display. I would prefer not to store the live variable in a database as creating a collection solely fo ...

Trouble with displaying days on the Datepicker

I'm currently facing an issue with my datepicker. I have a specific set of days that should be highlighted on the calendar, and it needs to be constantly updated. For example, past days are removed from the calendar automatically to keep it current. H ...

What are some solutions for resolving a background image that fails to load?

HTML: `<div class="food-imagesM imagecontainer"> <!--Page info decoration etc.--> </div>` CSS: `.food-imagesM.imagecontainer{ background-image: url("/Images/Caribbean-food-Menu.jpg"); background-repeat: no-repeat; backgroun ...

Update vue-table-2 to activate search filter upon button click, rather than keystrokes

exploring the capabilities of https://github.com/matfish2/vue-tables-2 using Vue.js version 2.6.11 Hey there! I'm a newbie developer delving into Vue.js after working in the React world. I'm aiming to modify the filter/search functionality to tr ...

Jasmine secretly observes the behavior of Angular services

I'm currently in the process of setting up unit tests for an angular controller using jasmine and karma. Due to the length of my code, I won't be able to include it all here. However, I'll provide some snippets: CompilerController.js (the c ...

Obtain additional information to address concerns related to onZoom and onPan issues on the line

Attempting to enhance my Chart.js line chart by fetching more data or utilizing cached backup data during onZoom/onPan events has proven quite challenging. The original code base is too intricate to share entirely, but I will outline the approaches I have ...

Limiting zero is ineffective when it comes to pop-up issues

Hey there, I'm looking to prevent users from inputting zero and dot in a specific field, which is currently working fine. However, when the field is within a pop-up, the code below doesn't seem to work. <script> $('#name').keyp ...

The checkbox is failing to display as checked even after its value has been dynamically set to true

Currently, I am immersed in a project within ASP.NET MVC that involves displaying data on a page where users can interact by selecting checkboxes to make changes. In cases where there are numerous checkboxes present, a "Select all Checkboxes" button become ...

In C#, transforming JSON serialization to replace single backslashes with double backslashes

When generating JSON to be included directly in an HTML file, it's important to wrap the JSON in a JavaScript string. For example: var dataContacts = '{"Contacts":[{"Id":0,"Active":false,"Company":"Rory The Architect\\, Melt"} ...

IE11 encounters an error labeled SCRIPT1010, signaling an expected Identifier when compiled

Lately, I've been encountering a strange issue in Vue.js. Here's the thing: my application runs smoothly on all browsers locally (yes, even IE 11). But when I compile it using npm run build and deploy it to my server (which essentially serves con ...

How can the border of the select element be removed when it is active in select2

After examining the CSS code, I am still unable to locate the specific property that is being applied to the main element. I am currently customizing the select2 library to suit my needs. However, I am stuck in the CSS as I cannot determine which property ...

Generating components dynamically at runtime following an HTTP request in VueJS

Is there a way to conditionally render VueJS components based on an Http request immediately upon application launch? I want to display component 1 if the response is successful, otherwise display component 2. Additionally, I would like the rendering of th ...

Generating Enums from JSON REST API in Angular 8

Is there a way to create an enum from a JSON REST API? Here is the code I currently have in my service.ts file: getDataFromJson(): Observable<any> { return this.httpClient.get<any>(`../../../assets/gender.json`) .pipe(map(data => ...

The React component is failing to display updated data from the Redux store

I've been working with React and Redux, trying to update my counter value in the React view. I can successfully log the latest state of my Redux store, but the changes are not reflecting in my React view. const counter = (state = 0, action) => { ...

The absence of a semi-colon in JSLint

I encountered an error message indicating a semicolon is missing, however I am unsure of where to place it. Here is the snippet of code: $('.animation1').delay(350).queue(function(){ $(this).addClass("animate-from-top") }); ...

Dissecting Distinct and Alphabetized Attributes in JSON/JavaScript

Below is a code snippet that retrieves and organizes a list of values from JSON data in alphanumeric order based on a specific key-value pair: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 &a ...