The behavior of the "checked" attribute in VueJS checkboxes does not always match their actual state

In this example, I have created a todo-list with checkboxes that can be checked or unchecked based on whether a task is completed or not.

If you uncheck a checkbox in the "Complete tasks" section, the next checkbox will also appear unchecked even if it is still checked in the "All tasks" section.

To see this issue in action, try unchecking the "Go to the store" task in the "Complete tasks" section. You will notice that the "Clean room" task appears unchecked, although it remains checked in the "All tasks" and holds completed status in the data.

Do you have any suggestions on how to resolve this inconsistency?

Answer №1

One challenge to be aware of is Vue's attempt to optimize and "reuse" the DOM, which may not always work in your favor.

To address this issue, it's essential to include a key for each element within a v-for, allowing Vue to differentiate between individual <li> elements based on their keys.

For more detailed information, refer to the documentation: https://v2.vuejs.org/v2/guide/list.html#Maintaining-State

<html>
<head>
    <title>VueJS</title>
</head>
<body>
<div id="root">
    <h1>All tasks</h1>

    <ul>
        <li v-for="task in tasks" :key="task.id">
            {{ task.description }}
            <input type="checkbox" v-model="task.completed" :id="task.id">
        </li>
    </ul>

    <h1>Complete tasks</h1>

    <ul>
        <li v-for="completeTask in completeTasks" :key="completeTask.id">
            {{ completeTask.description }}
            <input type="checkbox" v-model="completeTask.completed" :id="completeTask.id">
        </li>
    </ul>

    <h1>Incomplete tasks</h1>

    <ul>
        <li v-for="incompleteTask in incompleteTasks" :key="incompleteTask.id">
            {{ incompleteTask.description }}
            <input type="checkbox" v-model="incompleteTask.completed" :id="incompleteTask.id">
        </li>
    </ul>
</div>

<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84f2f1e1c4b6aab2aab5b6">[email protected]</a>/dist/vue.js"></script>

<script>
  new Vue({
    el: '#root',
    data: {
      tasks: [
        {id: 1, description: 'Go to the store', completed: true},

        {id: 2, description: 'Finish X', completed: false},

        {id: 3, description: 'Do Y', completed: false},

        {id: 4, description: 'Clear inbox', completed: false},

        {id: 5, description: 'Make Z', completed: false},

        {id: 6, description: 'Clean room', completed: true},
      ],
    },

    computed: {
      completeTasks() {
        return this.tasks.filter(task => task.completed);
      },

      incompleteTasks() {
        return this.tasks.filter(task => !task.completed);
      },
    },
  });
</script>
</body>
</html>

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

Steps for Removing a Single Distinct Entry from Every Table in MySQLWould you like to learn

These are the tables I'm working with Table1: id mark 01 80 02 100 Table2: id subject 01 80 02 100 I am trying to delete the record with id 01 from both tables simultaneously using a single query but the following code is not ...

multiples of order quantities in WooCommerce

In order to implement a minimum order quantity based on category, I came across this code. However, it seems to apply to all products in the cart. What additional modifications would be needed to specify certain categories? My objective is for customers t ...

Arrange the Json array by key value in a different order

I have a contact list that is returning in a lengthy form, organized based on order of entry. I am looking to alphabetically sort the list by displayName which is nested within the main array. Can anyone assist with this challenge using JavaScript? Thank ...

Ways to access UserProfile in a different Dialogio

For the implementation of a chatbot, I am utilizing Microsoft's Bot Builder framework. However, upon implementing an alternative path to the dialog flow, I noticed that the user's Profile references are getting lost. Here is the code snippet fr ...

What is the best way to simulate axios API calls in Jest for mocking purposes?

I am currently testing a Vuex action async function that calls an API using axios. However, I am facing an issue where I am getting an error message that says: "TypeError: Cannot destructure property data of 'undefined' or 'null'." 3 ...

The website is missing the display of Google Maps

The Google map is not displaying on my website page that uses PHP. I need assistance with this issue. Below is the webpage URL and the source code: <section class="meteor-google-map fullwidth block" style="height: 450px; border: solid transparent; bo ...

Setting a null image file in PHP after a successful AJAX operation can be accomplished by simply updating the

In my current project, I am working with Ajax and PHP. Upon clicking the post button, the message value gets removed using $("#message").val("") after a successful Ajax response (data insertion into the database via PHP and Ajax). Howev ...

Is there a way to have a button function as a submit button for a form even when it is located in a separate component within a react application?

I am in the process of creating a user-friendly "My Account" page using react, where users can easily update their account information. I have divided my components into two sections: the navbar and the form itself. However, I am facing an issue with the s ...

using eloquent in vuejs to fetch database columns

I am currently attempting to retrieve data from a database using an AXIOS get request. I have two models, Content and Word, which have many-to-many relationships. In my controller, I am trying the following: public function fetchCourses(){ $dayOne = C ...

Leverage Vue's ability to assign data from a parent component to

I am struggling to bind the data (inputData) from the parent component to my child component. I have checked my code multiple times but cannot find where the mistake is. MainApp.js let vm = new Vue({ el: "#app", components: { &ap ...

Selenium gets caught in endless loops

On my homepage, I have a variety of links that lead to different applications. Each link opens a new tab or window, where I need to check for the presence of a specific element using its XPath (which is provided from an Excel file for all applications). ...

Sending a Thunk to the store using Typescript

Within my primary store.ts file, the following code is present: const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)) ); store.dispatch(fetchUser()); Upon initial rendering, an action is dispatched to fetchUser in ord ...

Looping through ng-repeats, extracting checked checkbox values in Angular

I am currently dealing with multiple nested ng-repeats in my project, and the third level down consists of a group of checkboxes. Initially, I receive an array of options for these checkboxes, which I handle with the following code snippet: <div class= ...

JavaScript - Verify if all properties belonging to an object are set to true

I'm facing a challenge with an object that contains various fields which could potentially be set to true for a user, similar to a list of achievements. If I have an object like {one: true, two: false, three: true}, how can I prevent the function from ...

An AJAX request receives a "400 Error: Bad Request" status code

Recently delving into the realm of jquery, I've encountered a 400 bad request error (identified in the browser console). $("form#upload").submit(function(){ var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name=&apo ...

Navigating through Sails.Js: A Guide to Implementing Pagination

Looking to implement paginated tables in your application using sails.js, mongodb, and waterline-ORM? Wondering if there is a recommended method for pagination in sails.js? ...

Error: The variable 'error' could not be located

Below is the code that I am using: $(document).ready(function(){ var callPage = function(){ $.post('/pageToCall.php'); }; setInterval('callPage()', 60000); }); However, I encountered an error stating ReferenceErro ...

Incorporate a JavaScript variable into an HTML href link for dynamic web content

This is a snippet from my code: <p id="demo">{$value.file_name}</p> <script type="text/javascript"> var str = document.getElementById("demo").innerHTML; var res = str.replace("/var/www/html/biology/demo", ""); document.getElementById(& ...

Refresh Form Following Submission

When using a react form that triggers a graphql mutation upon button click, the text entered in the form fields remains even after the mutation has been executed. This necessitates manual deletion of text for subsequent mutations to be run. Is there a way ...

Chrome and Firefox provide excellent compatibility for running JavaScript, whereas Safari may encounter some issues. Opera's performance with JavaScript can be quirky

Disclaimer: I'm new to web design and development. I have encountered an issue with posting information from a form built on CodeIgniter using jQuery. The form posts successfully in Chrome and Firefox, with the current page automatically reloading. H ...