When Vue is clicked, it appears to trigger multiple methods simultaneously

Currently, I am learning Vue and encountered a problem that I need help with.

When using the v-on:click directive to call a method, all other instance methods are also called when the same method is used elsewhere.

HTML:

<div id="exercise">
    <div><button class="test" v-on:click="newCheck()">New Challenge</button>
        <p >Success check is: {{ passCheck }}</p>
    </div>
    <div>
        <button class="roll" v-on:click="roll20()">Roll!</button>
        <p>You Rolled a {{ roll20() }}</p>
    </div>
</div>

JS:

new Vue({
    el: '#exercise',
    data: {
        yourRoll: '10',
        passCheck: '10',    
    },
    methods: {
        roll20: function(){
            this.yourRoll = Math.round(Math.random()*19)+1;
            return this.yourRoll;
        },
        newCheck: function(){
            this.passCheck = Math.round(Math.random()*19)+1;
        }
    }
});

If {{ roll20() }} is used in the second paragraph, clicking the 'New Challenge' button triggers both roll20() and newCheck(). However, if {{ yourRoll }} is used instead, this doesn't happen.

Regardless, clicking 'Roll!' only executes the roll20() method.

Could someone please explain what exactly is happening here?

You can find a codepen illustrating the issue here: Codepen of code

Note: I managed to work around this problem by adopting a different approach, but I am still curious as to why this behavior occurred: Working Approach

Answer №1

If there are updates to the DOM, it will trigger the execution of roll20 again, thanks to this line:

<p>You Rolled a {{ roll20() }}</p>

This means that any change triggering an update will also trigger the roll20 function.


Let's consider the following template scenario:

<div><button class="test" v-on:click="newCheck()">New Challenge</button>

Pressing the New Challenge button will call the newCheck method.


Furthermore, since the newCheck method modifies a variable (passCheck) used in the template:

    newCheck: function(){
        this.passCheck = Math.round(Math.random()*19)+1;
    }

This variable is then utilized here:

    <p>Success check is: {{ passCheck }}</p>

Changing the value of

passCheck</code will provoke a DOM update, which in turn triggers the execution of <code>roll20</code (as explained in the first paragraph).</p>

<hr>

<h1>Solving the issue:</h1>

<p>A simple solution would be to avoid calling <code>roll20
directly in the template. Given that roll20 actually updates a property named yourRoll:

    roll20: function(){
        this.yourRoll = Math.round(Math.random()*19)+1;
        return this.yourRoll;
    },

You can simply use yourRoll directly in the template instead of calling roll20():

<p>You Rolled a {{ yourRoll }}</p>

CodePen example: https://codepen.io/acdcjunior/pen/PePBeo

Answer №2

<div id="exercise">
        <div><button class="test" v-on:click="newCheck()">Start New Challenge</button>
    <p >Success status: {{ passCheck }}</p>
    <!-- 3) Invoke a function to generate a random float between 0 and 1 (Math.random()) -->
        </div>
        <div>
        <button class="roll" v-on:click="roll20()">Roll Dice!</button>
    <p>You Got: {{ yourRoll }}</p> <!-- this changed -->
        </div>
</div>

new Vue({
    el: '#exercise',
    data: {
        yourRoll: '10',
        passCheck: '10',    
    },
    methods: {
        roll20: function(){
            this.yourRoll = Math.round(Math.random()*19)+1;
        },
        newCheck: function(){
            this.passCheck = Math.round(Math.random()*19)+1;
        }
    }
});

Give it a try, it works perfectly! Just remember to access your data property instead of calling the method directly! See it in action

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

Infusing JavaScript with vibrant images

I am currently facing an issue where I am trying to insert images with JavaScript attached to them. Oddly enough, it seems to work fine on Firefox but the images or icons do not display on Internet Explorer. This is how I have written the code: <a hre ...

Establishing a minimum width for the value of zero in AmCharts column series by customizing the bullet labels

Here's an interesting example where I have arranged column series with bullet labels. However, you may notice that there are some 0 values present as well. My goal is to establish a minimum width for the series so that even if the value is small or 0, ...

Integrate new functionality into the plugin's JavaScript code without directly editing the JS file

I need to incorporate a new function called 'setInputDataId' at the same level as the existing function '_select' in the plugin js file without directly modifying the file itself. I am seeking guidance on how to add this new function. ...

The form data should persist even if the user switches screens or logs out of the session, ensuring that the information remains intact

As a user fills out data in form input fields, ensuring that the entered values persist even if the user navigates to other pages or logs out of the session can be a challenge. How can we achieve this functionality in vue.js? Despite my attempts, I have no ...

What could be causing the QullJS delta to display in a nonsensical sequence?

The outcome showcased in the delta appears as: {"ops":[{"retain":710},{"insert":" yesterday, and she says—”\n“The clinic?","attributes":{"prediction":"prediction"}},{"del ...

Error: CSRF token not found or invalid. What is the procedure for transmitting a CSRF token from the frontend to the backend?

In my Django project, I have a task that involves sending a date string from the frontend to the backend. On the frontend, I am utilizing JavaScript's fetch method. async function getCustomerInDeliveryDate(deliveryDate : String) { con ...

What is the best way to selectively remove Tailwind styles from a single Vue component?

Currently, I find myself in a situation where I need to eliminate the broad impact of the global Tailwind CSS framework from a single specific component. My goal is to uphold a clean and concise HTML document free from unnecessary styling influences. To a ...

Preserve the chosen List group element with Vue.js

Currently, I am in the process of creating a Quiz application. The issue I am encountering is that when a user selects an answer, the selected list item class becomes active. However, if the user then chooses the answer to another question, the borders on ...

Tips for updating a nested MongoDB object

Looking to implement a reporting feature for my application When making a PUT request in the front end: .put(`http://localhost:3000/api/posts/report`, { params: { id: mongoId, ...

Is utilizing v-model to update the Vuex store a recommended practice?

Hello there! As a newcomer to Vue, I find myself facing a dilemma that has been weighing on my mind. I'm confused about whether we should utilize the v-model directive to make changes to the Vuex store. While Vuex guidelines suggest modifying the stor ...

transferring attributes from a component iterated over to a component it renders

Admitting my lack of expertise, I am seeking assistance with the implementation of the following code. This is my "posts" component responsible for making an API call to fetch all post data: import React from 'react' import Post from '../pos ...

Display a clock showing the Central Standard Time (CST) on an HTML webpage using

Is there a way to display the current time in CST time format on an HTML page using JavaScript? I need it to be shown in the following format: "02 Jul 2015 10:34:45 PM" ...

The Plupload internal version seems to be incorrect. The file is labeled as 2.3.9, however, the actual version within the file is 2.3

We recently identified a security vulnerability issue with plupload 2.3.6 being deemed as vulnerable. To address this, we downloaded version 2.3.9 from the official Plupload website here: Upon inspection, we found that the zip file is labeled as 2.3.9, bu ...

Hey there! I'm currently facing some difficulties with storing form input data into a nested json file

I have developed a Next.js application with a form component structured as follows: components/Form.js import { useState } from 'react' import { useRouter } from 'next/router' import { mutate } from 'swr' const Form = ({ for ...

Can security groups be dynamically updated using a JSON file in JavaScript rather than relying on manual parameters?

Looking to enhance security group rules, I aim to have my javascript file extract data from a separate json file instead of relying on json parameters directly. After initially using json parameters for security group updates, I am now exploring the metho ...

Is there a way to use JavaScript or jQuery to identify if Firefox is blocking mixed content

Is there a way to detect when Firefox (or any browser) is blocking mixed content using JavaScript or jQuery? To learn more about Firefox's mixed content blocking feature, visit: The backstory: My company has an external vendor that handles the onli ...

Give the Row ID as a parameter to a personalized component within MUI Datagrid Pro

I am currently exploring the idea of incorporating an intermediate state to row checkboxes based on the selection status of other checkboxes within a detailed panel. My approach involves crafting a custom checkbox component and implementing some logical ...

how to load CSS and JS files on certain views in Laravel 5.2

Currently, I am facing a situation where I need to ensure that the CSS and JS files are loaded only on specific views in Laravel 5.2. Due to my boss's decision to eliminate RequireJS for loading JS files on our blade templates, we are now exploring a ...

What could be causing my JavaScript code to not function properly in an HTML document?

Hello, I am a beginner in the world of coding and currently delving into web development. Recently, I was following a tutorial on creating a hamburger menu but I seem to be encountering some issues with the JavaScript code. I have double-checked my Visual ...

How can I apply and delete a css class only while scrolling in a React application?

Currently, I am designing a pretend blog layout to showcase my work. The grid of posts features cards that are precisely 400x400 in size with a hover effect that magnifies and adds a drop shadow (this is visible in the dashboard route). However, an issue ...