A guide on combining two counters in Vue to create a unified value

Is there a way to track the number of times two buttons are clicked individually as well as together?

<div id="app">
    <p><button v-on:click="counter1 += 1">Add One More Click</button></p>
    <p><button v-on:click="counter2 += 1">Add One More Click</button></p>
    <p>The total clicks on both buttons: {{ counter1+counter2 }} times</p>
    <p>Button 1 has been clicked: {{ counter1 }} times</p>
    <p>Button 2 has been clicked: {{ counter2 }} times</p>
</div>

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            counter1: 0,
            counter2: 0
        }
    })
</script>

I'd love some help in achieving this functionality using vue!

Answer №1

The issue with your code is that you are trying to increment `counter1` and `counter2`, but these variables are not defined in your code. Instead, you have `button1` and `button2`. Aligning the names of the variables should resolve this error.

One alternative approach would be to use a `computed` property to handle the addition of `counter1` and `counter2` within the template.

For example:

var app = new Vue({
  el: '#app',
  data: {
    counter1: 0,
    counter2: 0
  },
  computed: {
    totalClicks() {
        return this.counter1 + this.counter2;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <p><button v-on:click="counter1++">Add One More Click</button></p>
  <p><button v-on:click="counter2++">Add One More Click</button></p>
  <p>Total clicks: {{ totalClicks }}</p>
  <p>Button 1 clicks: {{ counter1 }}</p>
  <p>Button 2 clicks: {{ counter2 }}</p>
</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

Seamless changes with graceful fades while transitioning between classes

Is it more efficient to handle this in CSS than using jQuery? I'm not entirely sure. If anyone has a solution, that would be greatly appreciated. However, I am currently facing an issue with the jQuery method I have implemented. It successfully fades ...

Encountering issues with importing a module from a .ts file

Although I have experience building reactJS projects in the past, this time I decided to use Node for a specific task that required running a command from the command line. However, I am currently facing difficulties with importing functions from other fil ...

The datepicker in Vuetify is failing to display any dates

My date picker modal expands correctly, but the dates are not showing up. https://i.stack.imgur.com/azC1w.png The datepicker functions perfectly on the Codepen demo, displaying the dates as expected. However, when I try to implement the same code in my ap ...

Class variable remains unchanged following AJAX request

Upon completion of the ajax request, two integers are received - this.N and this.M. However, these values are not being set by the storeDims() function even though the correct decoding is done on the dims variable. This implies that I am unable to access ...

Why is the size of my array shrinking with every iteration of the for-loop in JavaScript?

I am struggling to change the classname of three elements that share the same classname. Unfortunately, as I loop through my array, it seems to decrease in size with each iteration, preventing me from successfully changing all three elements. Any advice or ...

Enhance your existing look by incorporating element.style into your designs

Is there a way to add styles onto an html element without overwriting existing css? element.style { "existing css;" } I'm trying to achieve the following result: element.style { existing css; opacity: 0; pointer-events: none; } But current ...

Is it possible that binding a ref is not functional in vue.js?

Whenever I use v-bind to bind an element reference with :ref="testThis", it appears to stop functioning. Take a look at this working version: <template> <div> <q-btn round big color='red' @click="IconClick"> ...

unable to perform a specific binary operation

Is there an efficient method to achieve the following using binary operations? First byte : 1001 1110 Second byte : 0001 0011 Desired outcome : 1000 1100 I am looking to reset all bits in the first byte that correspond to bit values of 1 in the secon ...

Scenario-specific blueprints

I'm currently facing a challenge in incorporating logic into a dustjs template, and I find it challenging to integrate all the components seamlessly. Here is an example of the JSON data I have: { "names": [{ "name": "User 1", "is ...

Unable to include Authenticated Routes in react router dom

Currently, I am utilizing react-router-dom to manage routing for users who are authenticated and non-authenticated. However, I have encountered an error in Element due to missing properties. Is there a way to make withoutAuth() function properly for authe ...

Add a fresh category to a JSON document

Combining Express (Node.js) and Mongoose, I am developing a REST API and attempting to implement JWT token-based login. However, I have encountered an issue. Upon executing the code below: const mongoose = require('mongoose'); const User = mongo ...

Managing multiple to-do lists within a React application using parent-child relationships

ReactJS has a flaw that I've come across while trying to create a Todo application using Redux for state management. The issue arises when dealing with nested JSON data, such as having parent and child nodes in the response from a database query. Red ...

What is the correct way to set up Cypress intercepts within a beforeEach function?

As a newcomer to Cypress, I find some aspects of it challenging despite its apparent simplicity. I am facing a specific issue: const componentsRouteMatcher = { pathname: '/component-management/api/components', query: { size: &apos ...

The ngOnInit function is not triggered upon instantiation of an Injectable class

What could be causing the ngOnInit() method not to be called upon resolution of an Injectable class? Code import {Injectable, OnInit} from 'angular2/core'; import { RestApiService, RestRequest } from './rest-api.service'; @Injectable ...

Ways to conceal buttons according to your 'occupation'?

I am currently developing an application and I would like to have certain buttons displayed based on the user's $job. There are four job roles stored in mysql databases: student teacher staff principal, The signup button should only be visible to te ...

Toggle divs by using a checkbox (Vue.js)

On my authentication page, I have implemented a checkbox that I want to use to toggle between Sign Up and Sign In forms. When the checkbox is clicked, it should display the Sign Up form, and when it's unchecked, it should show the Sign In form. I fou ...

How can you match something once in NodeJS?

I am experiencing an issue with my HTTP NodeJS server - every time I visit the URL, it outputs the result twice. const https = require('http'); const fs = require('fs'); const url = require('url'); https.createServer((req, r ...

Swap out the image for a div element if the image is not found

Is there a way to accurately display an image if it's available, and use a div as a replacement if the image is not present? // How can I determine `imageExists` without encountering cross-origin issues? (imageExists) ? (<img class="avatar-img" sr ...

What are the differences between a Chrome app and extension? Is there any other way to access the tabs currently open in your

I need to develop an app that can access the tabs a user has open, but I'm struggling to find a way to do so without having my app run in Chrome itself. Creating an extension restricts the UI significantly, which is problematic since my app requires a ...

Attaching a click event to an input field

Seeking to serve html files from the server without relying on template engines. Below is the script used to start the server. // script.js const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(expr ...