Fixing issue with Vue.js property not consistently triggering events

I have a snippet of HTML code that includes a Vue.js script:

<!DOCTYPE html>
<html>

<head>
    <script src="vue.js"></script>
</head>

<body>
    <div id="app">
        <input type="checkbox" :checked="bool" @change="checked(this)">
    </div>
    <script>
        var app = new Vue({
            el: "#app",
            data() {
                return { "bool": true }
            },
            methods: {
                checked(elem) {
                    console.log("Hey!");
                    // Cast to bool
                    this.bool = !!elem.checked;
                }
            }
        })
    </script>
</body>

Although I am planning on incorporating more complex functionality, I have chosen not to use v-model.

When the checkbox is clicked, the console displays a message every time. However, the bool property seems to only update the first time the checkbox is clicked, and not on subsequent clicks. Can anyone suggest what might be causing this issue?

Answer №1

Apologies for the confusion. The element raising the event is not this, but rather the global window object. To access the element, you can use event.target as shown below:

<input type="checkbox" :checked="bool" @change="checked('Hi!', $event)" id="check">
this.bool = !!event.target.checked;

https://forum.vuejs.org/t/change-in-vue-js-property-from-event-only-firing-once/88105/2

Credit goes to @an_parubets for helping reveal this solution!

Answer №2

Combining two exclamation marks !! results in the cancellation of each other, leading to no change.

To achieve the desired outcome, you can simply use the following code:

this.bool = !this.bool

This snippet would effectively toggle the value of 'bool' as shown below:

methods: {
  checked(elem) {
     console.log("Hey!");
     this.bool = !this.bool;
   }
}

Answer №3

The issue arises from the immediate call to the event handler: @change="checked(this)". If you wish to interact with the event, handle it as follows:

Template:

<div id="app">
   <input type="checkbox" :checked="bool" @change="checked('Arguments', $event)">
</div>

Method:

methods: {
  checked(argument, event) {
    console.log(argument);
    this.bool = !!event.target.checked;
  }
}

If there is no need for event access, a simpler approach can be utilized:

<div id="app">
   <input type="checkbox" :checked="bool" @change="bool = !bool">
</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

The Facebook JavaScript API function FB.api() is limited to posting messages and does not support media attachments

I am attempting to share a message with an mp3 attachment on the active user's wall. It works perfectly fine within Facebook's Test Console, but when I try it from my mobile app, only the message gets posted. Can anyone help me figure out what I ...

The Meteor method is unable to access the property "quantity" as it is undefined

I encountered an issue with the error message "TypeError: Cannot read property 'quantity' of undefined" while executing a meteor method. Here is the frontend call: Template.listingPage.events({ "submit #add-to-cart": function(e,t){ e.preven ...

Unable to retrieve information from JSON using jQuery's AJAX method

My journey with learning JSON using jQuery has hit a bump in the road. Despite spending two days and going through various tutorials on YouTube and blogs, I'm facing a challenge. The JSON structure presented in the tutorials differs from the one I hav ...

Locating the position of multiple repeated words

My question involves a complex laTeX string: let result = "\\frac{x}{2}+\\frac{3}{x}"; The task at hand is to locate the instances of "frac" in the string, store their positions in an array, find the first '}&a ...

Can we accurately pinpoint individual LineSegments in three.js by hovering over them, especially those with unique geometries?

Creating two examples of drawing lines in three.js was quite a fun challenge. One example showcased different geometry and material, while the other kept it simple with just one geometry and material. The demonstration links can be found here: Example 1 an ...

One specific JS file fails to load only when using Internet Explorer Browser in conjunction with the debugger

I am encountering an issue with a project that utilizes angular JavaScript controllers to populate fields. Unfortunately, a specific page, members.cshtml, is not loading properly in Internet Explorer 11, despite working perfectly on Chrome and Firefox. Af ...

I'm struggling to solve a straightforward jQuery sliding issue

I am struggling to make text slide from right to left on my website. I want the text to appear only when the page loads or refreshes, and then slide off when a link is clicked, revealing new text. Can anyone help me figure this out? http://jsfiddle.net/XA ...

Header vanishes while using a JavaScript function to search through an HTML table

I'm facing an issue with a search function in a php script. The search function, written in javascript, is designed to sift through the table below and extract matching content as the user inputs text into the search field. It looks specifically withi ...

Refresh your webpage automatically without the need to manually refresh after clicking a button using AJAX in HTML and PHP!

One issue I'm facing is that the page doesn't auto-refresh, although it loads when I manually refresh it. Below you can find my HTML and AJAX code along with its database details. The Trigger Button <?php $data = mysqli_ ...

Exploring Next.js dynamic imports using object destructuring

import { UDFCompatibleDatafeed } from "./datafeeds/udf/src/udf-compatible-datafeed.js"; I'm facing a challenge in converting the above import to a dynamic import in Next.js. My attempt was as follows: const UDFCompatibleDatafeed = dynamic(( ...

Unable to interpret data from the API

{ id: 8, customerName: "xyz", customerMobileNumber: "123456789", customerBillingAddress: "xyz address", customerShippingAddress: "xyz address", customerProductPurchasedDate: "2021-11-09T09:07:00.000Z", cust ...

Transfer a variable from one PHP page to another and navigate between the two pages

I am just starting to learn PHP and I have a scenario where I need to retrieve the last ID from the database. For each ID, I need to fetch the state and the associated link. If the state is equal to 1, then I need to extract some content from the link (whi ...

What is the most effective way to showcase a list of image URLs in HTML with Vue?

Currently, I am working with an array called thumbnails that holds the paths to various images. My goal is to use masonry in Vue to arrange these images in a grid format, but I'm encountering some difficulties achieving the desired outcome. This is m ...

Generate an automatic "proxy" for ASP.NET MVC Controller to communicate with AngularJs service

Whenever I utilize an ASP.NET MVC controller with AngularJS, the majority of my controller functions consist of JSON results. When creating my AngularJS service, I find myself repeatedly writing similar code to handle GET or POST calls to my ASP.NET contro ...

Using PHP to extract all occurrences of window.location from an HTML document using regex

Is there a way to extract all the window.location instances in PHP? I have a list of URLs that I am fetching using cURL, saving the HTML content as a string, and now I need to identify and display all the occurrences of window.location separately. I atte ...

Javascript editing enhancement for real-time changes

Are there any tools for in-place editing of Javascript code? I'm looking for something similar to Firebug, which is great for instant CSS editing and previewing but doesn't have the capability to edit JavaScript directly. Is there a tool or addon ...

Tips for dynamically styling a Styled Component with all the CSS housed in an external file

My goal is to dynamically render a Styled Component. In the past, it was simple because all styling was contained within the component itself. However, I now strive to maintain a separation of concerns by storing the CSS in an external file. While this app ...

Enhance the original array of a recursive treeview in VueJS

After going through this tutorial, I decided to create my own tree view using recursive components in Vue.js. The structure of the input array is as follows: let tree = { label: 'root', nodes: [ { label: 'item1', nod ...

sending properties to dynamically loaded components

I'm struggling with transferring props between children and parent components using Vue Routes. Within my Layout component, I have a wrapper DIV structured like this: <template> <div class="container" v-bind:class="cssClass ...

I keep encountering a 'Missing Permissions' issue whenever I attempt to execute the ban command in Discord.js. What could be causing this problem?

While working on coding a ban command for my Discord server, I encountered an issue where the command was not working as expected. Upon testing, I received an error message on the console stating DiscordAPIError[50013]: Missing Permissions. This was puzzli ...