Whenever a click event is triggered, the Vue method is executed twice

Why is the set method being executed twice? Check the console when you click the star. Removing @click="set(rating)" results in no action, indicating it is not called elsewhere.

http://jsfiddle.net/q22tqoLu/

HTML

<div id="star-app" v-cloak>
            <star-rating value="0"></star-rating>
        </div>

        <template id="template-star-rating">
            <div class="star-rating">
                <label
                class="star-rating__star"
                v-for="rating in ratings"
                :class="{'is-selected': ((value >= rating) && value != null), 'is-disabled': disabled}"
                @mouseover="star_over(rating)"
                @mouseout="star_out"
                @click="set(rating)">
                <input
                class="star-rating star-rating__checkbox"
                type="radio"
                :name="name"
                :disabled="disabled"
                :id="id"
                :required="required"
                v-model="value">
                ★
            </label>
        </div>
    </template>

JS

  'use strict';

    Vue.component('star-rating', {
        template: '#template-star-rating',
        data: function data() {
            return {
                value: null,
                temp_value: null,
                ratings: [1, 2, 3, 4, 5]
            };
        },
        props: {
            'name': String,
            'value': null,
            'id': String,
            'disabled': Boolean,
            'required': Boolean
        },
        methods: {
            star_over: function star_over(index) {
                if (this.disabled) {
                    return;
                }

                this.temp_value = this.value;
                this.value = index;
            },
            star_out: function star_out() {
                if (this.disabled) {
                    return;
                }

                this.value = this.temp_value;
            },
            set: function set(value) {
                if (this.disabled) {
                    return;
                }

          // This runs twice
          console.log(value);

                this.temp_value = value;
                this.value = value;
            }
        }
    });

    new Vue({
        el: '#star-app'
    });

This code is a modified version based on an older version by someone else. You can also find a similar example that doubles here.

Answer №1

By placing @click="set(rating)" on the <input/> element rather than the <label/>, the function will only execute once.

Answer №2

@click.stop="clicked($event)"

By using this method, further calls will be prevented and the function will only be executed once.

Answer №3

This is a common occurrence in browsers by default. When you click on the <label> element, it triggers two separate clicks - one for the <label> itself and another for the associated <input>.

To prevent this behavior, you can simply apply the @click.prevent directive to your <label> tag.

Answer №4

In case it has no impact on your project, consider switching the event from click to mouseup.

@mouseup="set(rating)"

Answer №5

For my situation, I employed the prevent attribute for @click and @submit events to prevent bubbling.

@click.prevent="action"
@submit.prevent="action"

Answer №6

Instead of using @click.once='set(rating)', you can utilize this code snippet to ensure the function is only executed one time.

Answer №7

It would be beneficial to upgrade to the latest version of Vue. Here is the link to download it: https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js The current version you are using, 0.12.16, is quite outdated and may be causing the issue you are experiencing, which appears to be a bug specific to this older version. You can easily adjust this in your settings under JavaScript.

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

What is the best way to display a string state value in a React component?

I need assistance with displaying a state value that is in string format. Despite my efforts, I have not been successful in finding a solution and am feeling quite frustrated. Can anyone provide some guidance? ...

The Swiper/vue useSwiper() function is malfunctioning, resulting in an empty undefined value

After creating my navigation, I attempted to utilize the useSwiper method for button control. However, this method appears to be empty. Even after creating an example in the sandbox that mirrors my code, normal navigation works fine. But upon trying to imp ...

Exploring GridJS Customization in VueJS

Currently, I am working on a project using Vue V.3 and incorporating Grid.JS for my tables. I have been trying to figure out if there is a way to customize the styling of the table elements within Grid (such as th, tr, etc). Despite referring to the offi ...

Sending information to @select of multiselect in Vue.js - vue-multiselect

I'm currently working on passing a parameter to the @select event function in Vue.js HTML <template> <div class="container"> <div v-for="(billItem, k) in billItems" :key="k" > <div class=&q ...

Leveraging Arrays with AJAX Promises

I am currently working on making multiple AJAX calls using promises. I want to combine the two responses, analyze them collectively, and then generate a final response. Here is my current approach: var responseData = []; for (var i=0; i<letsSayTwo; i++ ...

Utilizing AXIOS and .NET 5 Web API for Managing Access and Refresh Tokens

In my React application using Redux, we are utilizing Axios to interact with our Web API. To ensure security, we have implemented JWT access tokens along with refresh tokens. The server side token generation for our Web API is based on this code: https:/ ...

Leverage JavaScript to retrieve the formatting of an element from an external CSS stylesheet

Check out this HTML snippet: <html> <head> <link rel="stylesheet" type="text/css" media="all" href="style.css"> </head> <body> <div id="test">Testing</div> <script> ...

Show the button's value on the text box using JavaScript

When using bootstrap, I encountered an issue where the value of a button would display in a textbox upon clicking it, but then quickly disappear. This unexpected behavior left the textbox empty prematurely. <input type="submit" value="5000t "class="btn ...

Determining a User's Connection Status in ReactJS: Cellular Network or WiFi?

Are there any tools or applications available that can determine if a user is connected to WiFi or using a cellular network? ...

The styling of the CSS is tailored to various breakpoints

source: Display helpers How can I dynamically change CSS styles based on the current breakpoint size? For example, can I set different sizes, positions, and colors for elements when the window is on xs compared to md or other breakpoints? ...

Is there a method to delay the loading of a webpage until an image has fully loaded (preloading)?

How can I ensure that an image used in a preloader is loaded before the other contents on my website? <div class="overlay" id="mainoverlay"> <div class="preloader" id="preloader"> <img src="images/logo128.png" id="logo-p ...

The form inputs within the modal are unresponsive to clicks

I recently began using bootstrap modals and had a separate register/login page from the index. I thought incorporating the login/register form into modals would be a good idea. However, inside the modal, all the inputs are not clickable - only accessible v ...

Dealing with the issue of receiving raw JavaScript in the .ajax error function even when receiving a 200

I am encountering an issue with a jQuery.ajax() call to a third-party product. The POST request is successful, returning a 200 OK status code, but instead of executing the success function, it redirects to the error function. The response variable displays ...

What is the best way to break down this function from props in React?

Forgive me if this question sounds naive, but as I delve into the world of React and useState, I am encountering a scenario where I have a signup function coded. Upon sending a username and password through a POST request to an API endpoint, a response mes ...

The MessageError: expressjs is unable to read the property "image" because it is null

I am currently working on developing a shopping cart using express and mongodb. However, I encountered an error when attempting to include an image category in the form. Here is the code snippet for handling post requests in admin_product.js: router.post(& ...

Selecting the content within a table to easily edit it

I am working on a project where I have a table filled with data fetched from a database. My goal is to allow users to click on a cell in the table, make changes to its content, and then save those changes back to the database. Below is the code snippet I a ...

What is the best way to send information from an MVC controller to JavaScript?

Being new to programming, I am working on 2 projects that function as client-server via Rest API. I am looking to create a column chart using data from a List of ID (participant) and Votes (Total votes) obtained from the server's connection with the d ...

What is the best approach for handling an AJAX request on the server side?

Consider the function below: $.ajax({url:"http://127.0.0.1:8080", data: "123", success: function(response, textStatus, jqXHR) { alert(response); }, error: function(jqXHR, textStatus, errorThrown) { alert("An er ...

Using jQuery to Navigate through Different Routes in React Router

Hey there, I've managed to get my React-Router set up quite well but now I'm facing a new challenge. I need to implement some JavaScript functionality. For example: When the user enters their login details and clicks 'login', I want my ...

Exploring the world of two-dimensional arrays in D3 programming

I am interested in visualizing data obtained from the census data API, specifically from the ACS survey. The data is not in a typical JSON format, but rather as a two-dimensional array. It appears like this: [ [ “POPULATION”, “DATE”, ...