Vue.js event change method does not initiate the trigger

I have been attempting to implement a change event in my Vue application, where a statement switches between true and false each time I check a checkbox. However, the functionality doesn't seem to be working as expected.

This issue arose while following along with a tutorial that inspired me to experiment by adding this change event.

<div v-for="task in tasks" :key="task.id" v-if="task.completed">
  <ul>
  <li v-text="task.description"></li>
  <input type="checkbox" @change="changeComplete">
  </ul>
</div>




var app = new Vue ({
  el: '#root',
  data:  {
    tasks: [
           {description: 'clean room', completed: true, id: 1},
           {description: 'do homework', completed: true, id: 2},
           {description: 'go to sleep', completed: false, id: 3}
           ]
          },
  methods: {
    changeComplete() {
          this.task.completed = !this.task.completed;
          }
      }
  })

Despite expecting the completion status of a task to toggle when its checkbox is checked, the change event fails to trigger, leaving the completed value unaltered.

Answer №1

If there is no task property within the data object, you will need to make changes in the tasks array instead. In order to do this, you must pass an index to identify which task needs to be modified.

var app = new Vue ({
  el: '#root',
  data: {
    tasks: [
           {description: 'clean room', completed: true, id: 1},
           {description: 'do homework', completed: true, id: 2},
           {description: 'go to sleep', completed: false, id: 3}
           ]
          },
  methods: {
    changeComplete(index) {
          this.tasks[index].completed = !this.tasks[index].completed;
          }
      }
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<div id="root">
<div>
<div v-for="task,index in tasks" :key="task.id" v-if="task.completed">
  <ul>
  <li v-text="task.description"></li>
  <input type="checkbox" @change="changeComplete(index)">
  </ul>
</div>
</div>
</div>

Alternatively, you can simply modify the class to switch or toggle the status of the task

var app = new Vue ({
  el: '#root',
  data: {
    tasks: [
           {description: 'clean room', completed: true, id: 1},
           {description: 'do homework', completed: true, id: 2},
           {description: 'go to sleep', completed: false, id: 3}
           ]
          },
  methods: {
    changeComplete(index) {
          this.tasks[index].completed = !this.tasks[index].completed;
          }
      }
  })
.completed{
  color: green;
  text-decoration: line-through;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<div id="root">
<div>
<div :class='{completed:task.completed}' v-for="task,index in tasks" :key="task.id">
  <ul>
  <li v-text="task.description"></li>
  <input type="checkbox" @change="changeComplete(index)">
  </ul>
</div>
</div>
</div>

Answer №2

In order to complete the desired task, make sure to reference it within the callback:

@change="changeComplete(task)"

Then implement the following code:

changeComplete(task) {
    task.completed = !task.completed;
}

If your v-if statement is meant to display incomplete tasks, ensure it's checking for uncompleted ones:

v-if="task.completed == false"

Below is a functional example:

Vue.config.productionTip = false;
Vue.config.devtools = false;

var app = new Vue({
  el: '#root',
  template: '<div> \
    <div v-for="task in tasks" :key="task.id" v-if="task.completed == false"> \
      <ul> \
        <li> \
          <span v-text="task.description"></span> \
          <input type="checkbox" @change="changeComplete(task)"> \
        </li> \
      </ul> \
    </div></div>',
  
  data: {
    tasks: [{
        description: 'clean room',
        completed: false,
        id: 1
      },
      {
        description: 'do homework',
        completed: false,
        id: 2
      },
      {
        description: 'go to sleep',
        completed: false,
        id: 3
      }
    ]
  },
  methods: {
    changeComplete(task) {
      task.completed = !task.completed;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="root"></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

deleting the current product information during an ajax request

After executing the query provided below, I have $product_list in this code. However, I want to use ajax so that when I click on the button link1, $product_list gets emptied. How can I clear the content within products_list using an ajax call triggered by ...

NodeJS presents a potential maze of confusion with its promises

I've been struggling to grasp the concept of asynchronous code execution in NodeJS. My goal is to fetch the output of ip a on a Linux machine and extract the IP Subnet manually. Once that is done, I simply want to use console.log() to display the IP S ...

What is the most effective way to save numerical information to a file?

Imagine a scenario where there is an array filled with one million random numbers: [ 0.17309080497872764, 0.7861753816498267, ...] The task at hand is to store these numbers onto a disk for future retrieval. While storing them in text formats like JSON or ...

Challenges encountered while formatting Json strings for WCF service transmission

I need assistance in connecting a JavaScript application to a WCF service. The WCF Service I have includes the following method: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFor ...

Struggling to iterate through the response.data as intended

Assume that the response.data I have is: { "data": { "person1": [ { "name": .... "age": xx } ], "person2": [ { ...

Choose the initial division within the table and switch the class

Here is a straightforward request - I need to employ jquery to target the first div with the class of "boxgrid captionfull" within the tr element with the classes "row-1 row-first," and switch the class to 'active_labBeitrag'. <table class="v ...

I am implementing a new method in the prototype string, but I am uncertain about its purpose

I am trying to wrap my head around the concept here. It seems like the phrase will pass a part of an array, in this case eve, to the phrase.palindrome method. This method will then process it. First, the var len takes the length of eve and subtracts 1 from ...

When employing vue.set within Vuex, it seems that the state is not getting properly updated

Today, I encountered an issue while trying to add an object into a nested array. Despite successfully using similar code for other states, it does not seem to be working this time around. I can't help but wonder if the problem lies in the fact that i ...

Send dropdown selections to a Javascript function and convert them into an array

Within my JavaScript function, I need to pass multiple selected values from dropdown menus and store them in a JavaScript array. Each time a value is selected and sent using the onchange() function, it should be added to the array. If the same value is sel ...

Determine the maximum and minimum numbers by inputting a number and utilizing jQuery

<script type="text/javascript"> function findLargestNumber() { var number1, number2; number1 = Number(document.getElementById("N").value); number2 = Number(document.getElementById("M").value); if (number1 > numb ...

Enhance the material-table component by incorporating dynamic information into the lookup property

I am currently facing challenges while attempting to dynamically add data to the lookup property in the Material-Table component. The lookup is structured as an object, and you can refer to its definition in the initial example provided here. However, it ...

Fetching an item from Local Storage in Angular 8

In my local storage, I have some data stored in a unique format. When I try to retrieve the data using localStorage.getItem('id');, it returns undefined. The issue lies in the way the data is stored within localStorage - it's structured as a ...

The image zoom function is malfunctioning when trying to adjust the image position

Having some trouble with a code for image zoom in/out. When I adjust the position of the image by applying margin left to either the image or the image container (#view), it affects the zoom functionality - causing the image to move to the left during zoom ...

Angularjs Error Message: Syntax Parsing Issue

Being new to AngularJS, I am trying to grasp the error messages displayed in the console. Below are my JSON object and other details for reference. In the JSP page: <body id="bodyID" ng-controller="ApplicationParameterController" > <div ng-c ...

Tips for solving the "jQuery needs a window with a document" error when using import statements

I'm encountering the "jQuery requires a window with a document" error, and it appears that I require guidance similar to this solution: Error: jQuery requires a window with a document My quest is to find the precise syntax for addressing this using i ...

Do AngularJS applications function similarly to windows?

Do AngularJS apps behave like windows? And is it possible to add an event listener to them? I am currently working on a proof of concept to see if an Angular app can communicate with a server without impacting the host. One potential solution I have thou ...

Is it normal for the protractor cucumber tests to pass without observing any browser interactions taking place?

Having recently started using protractor cucumber, I have created the following feature. Upon launching protractor protractor.conf.js, the browser opens and immediately closes, displaying that my tests have passed. Is this the expected testing behavior? Sh ...

Why does the Hamburger Menu shift my website's logo when it opens?

I'm in the process of implementing a hamburger menu on my website. My attempts have involved adjusting the positioning of both the #logo and .topnav elements. Code Snippet source function myFunction() { var x = document.getElementById("myTopn ...

Is it better to append content in JQuery rather than replacing it with .innerHTML?

Here is a function designed to retrieve older wallposts from a user, 16 at a time, and add each chunk of 16 to the end of the current list in the div called "sw1". The function works well, except when there is a wallpost containing a video or embedded obj ...

Apply a dynamic function to assign a background color to a specific class

Currently, I have a function called getBackground(items) that returns a background color from a JSON file list. Within my application, there is a component that automatically adds a class name (.item-radio-checked) when a user clicks on an item in the list ...