Unexpected behavior in VueJS code - troubleshooting the issue

In my VueJs code, I have a simple task list with completed and incomplete tasks. When I check or uncheck the box, the task should move to the appropriate list.

var app = new Vue({
  el: '#vueapp',
  data: {
    tasks: [{
        id: 1,
        description: 'Do some Stuff',
        completed: false
      },
      {
        id: 2,
        description: 'Go to pharmacy',
        completed: false
      },
      {
        id: 3,
        description: 'Go to doctor',
        completed: true
      },
      {
        id: 4,
        description: 'Do some Slask',
        completed: false
      },
    ]
  },
  methods: {
    toggleTask(key) {
      this.tasks[key].completed = !this.tasks[key].completed;
    }
  },
  computed: {
    incompleteTasks() {
      return this.tasks.filter(task => !task.completed);
    },
    completedTasks() {
      return this.tasks.filter(task => task.completed);
    },
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="vueapp">
  <h2>Completed Tasks</h2>
  <ul>
    <li v-for="(task, key) in completedTasks">{{ task.description }}<input type="checkbox" v-model="task.completed"></li>
  </ul>

  <h2>Incomplete Tasks</h2>
  <ul>
    <li v-for="(task, key) in incompleteTasks">{{ task.description }}<input type="checkbox" v-model="task.completed"></li>
  </ul>
</div>

When tested in Chrome, if you try to check the first incomplete task, it successfully moves to the upper list, but then the next incomplete task also gets checked. Be aware of this bug!

Answer №1

Make sure to include a key in your loops like this: :key="task.id".

By providing a unique key attribute for each item in Vue, you help the framework track each node’s identity, enabling it to reuse and rearrange existing elements effectively. It is recommended to use the unique id of each item as the key value.

var app = new Vue({
  el: '#vueapp',
  data: {
    tasks: [{
        id: 1,
        description: 'Do some Stuff',
        completed: false
      },
      {
        id: 2,
        description: 'Go to pharmacy',
        completed: false
      },
      {
        id: 3,
        description: 'Go to doctor',
        completed: true
      },
      {
        id: 4,
        description: 'Do some Slask',
        completed: false
      },
    ]
  },
  methods: {
    toggleTask(key) {
      this.tasks[key].completed = !this.tasks[key].completed;
    }
  },
  computed: {
    incompleteTasks() {
      return this.tasks.filter(task => !task.completed);
    },
    completedTasks() {
      return this.tasks.filter(task => task.completed);
    },
  }
});
.as-console-wrapper { display: none !important; }
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="vueapp">
  <h2>Completed Tasks</h2>
  <ul>
    <li v-for="(task, key) in completedTasks" :key="task.id">{{ task.description }}<input type="checkbox" v-model="task.completed"></li>
  </ul>

  <h2>Incomplete Tasks</h2>
  <ul>
    <li v-for="(task, key) in incompleteTasks" :key="task.id">{{ task.description }}<input type="checkbox" v-model="task.completed"></li>
  </ul>
</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

Can you explain the meaning of EPS in the THREE.OrbitControl function?

The this.update method within the THREE.OrbitControl script contains a private variable called EPS, which is used to adjust the phi angle. The following code snippet demonstrates how it restricts phi to be between EPS and PI-EPS: // restrict phi to be bet ...

I'm looking for a way to convert an array value to JSON using jQuery

i need assistance in converting an array value into json format. An example is provided below: Sample Array [Management Portal!@!@Production Issue Handling!@!@/IONSWeb/refDataManagement/searchDynamicScripts.do, Management Portal!@!@ Event Browser!@!@/ION ...

Unable to pass an Array to the Controller

let formData = new FormData(); payloadData = JSON.stringify(payload.unitDoctors); for (var prop in payloadData) { formData.append(prop, payloadData[prop]); } axios({ method: "put", url: apiUrl + payload.id, data: formData }) .then(resp ...

Is it possible to have unique color tags in Material UI Autocomplete?

I'm currently diving into the world of material-ui and encountering some challenges that I could use help with. I am trying to incorporate multiple arrays into the autocomplete menu (e.g., options={top100Films, top100Shows}, but with the correct sy ...

What method is the most effective for retrieving the prior slug name in NextJS?

Looking for Help with Retrieving postID? Greetings! I am currently working on a basic post detail page using NextJS. My URL structure is: [postID]/[title].tsx On the post detail page, I need to fetch the post's data based on the postID, which is hig ...

How can I retrieve the OptionID value upon click?

How can I retrieve the value of OptionID when the Add button (.plus-link) is clicked? Each list item may contain a dropdown select menu or not. <ul> <li> <div class="menux"> <div class="text-block"> ...

React Table in Modal Using Custom Hook State

I'm facing some difficulties with the React useState hook. Currently, I have a modal that pops up after submitting a form. Before loading the modal, the application calls an API to fetch data, which is then displayed in a table within the modal. The ...

Devices such as CAC cards and smart cards are not being recognized by Chrome's WebUSB feature

I recently developed a script to identify all USB devices connected to Chrome using chrome.usb.getDevices. Surprisingly, the script successfully detected a second-generation iPod touch, a mouse, keyboard, and two unidentified items from Intel. However, it ...

Adjust the width of xAxis[0] and xAxis[1] in Highcharts to their default values

Hi there, I need some help with Highcharts. Is it possible to adjust the width of xAxis[0] and xAxis[1] as well as reset the offset of xAxis[1] at runtime? I have a chart with two x-axes that need to be resized to fit different sized divs. You can see an ...

Troubleshooting the Width Problem in Bootstrap 5 Dropdowns

I am currently working on a new project and encountering an issue with the width of a Bootstrap 5 dropdown. The problem lies in the discrepancy between the button width and the menu width. Although it may seem simple, I am having trouble resolving it as I ...

I am looking to modify the background color of characters in a text box once the characters in a textarea exceed 150 characters

Currently, I am utilizing event.data to capture the text inputted into this particular HTML textbox. My intention is to change the background color to red based on that input. However, when using the style attribute on event.data, I encounter an error. It& ...

I attempted to verify the login through postman, but encountered an error in the process

I created the login route on the backend and tested it in Postman, but encountered this error message: https://i.stack.imgur.com/PdyCo.png Below is the code for the login route: router.post("/login", async (req, res) => { try { const user = await ...

I seem to be facing some issues while trying to create an avatar bot on discord.js

I'm trying to create a command for my bot that shows the user's avatar, but I keep running into an issue: DiscordAPIError: Cannot send an empty message at RequestHandler.execute (C:\Users\Pooyan\Desktop\PDM Bot Main\n ...

A step-by-step guide on storing JSON data into a variable using NodeJS

Just starting out with Node.js and running into an issue. I need to figure out how to extract and save data from a JSON object retrieved from the GitHub API. var http = require("http"); var express = require('express'); var app = express(); var ...

Using jQuery, how can you make fixed elements fade as the page scrolls?

How can I make a fixed element, such as a corner ad or notice, fade when the page is scrolled down to a certain point? What would be the most effective method for determining this point: using pixels, percentage, or another way? And how can I implement th ...

Proceed to the next request after the initial request has finished executing in node

Imagine there is an endpoint called /print. Each time a request is sent to this endpoint, it triggers the function printSomething(). If another user hits this endpoint while printSomething() is still processing, it will run the function again simultaneousl ...

Scroll through the menu with ease

I am facing an issue with my menu that has 2 levels. Whenever I try to scroll down, I want the position of the Logo to change to the bottom of the menu smoothly. However, during scrolling, there is a noticeable shake in the menu movement which makes it app ...

Issue encountered when trying to use Array.sort() method to sort an array of objects

I'm facing an issue sorting an array of objects by a name property present on each object. When utilizing the sort() method with the given code snippet, I encounter the following error: ERROR ReferenceError: b is not defined This is my code block: m ...

What could be causing this hydration error in NextJS in the development server build but not in the production build?

By using the create-next-app command and implementing this code snippet, a hydration error occurs on the client side when running the next dev server. The code in pages/index.js: export async function getServerSideProps(context) { const x = Math.random( ...

Tips to prevent encountering the "The response was not received before the message port closed" error while utilizing the await function in the listener

I'm currently in the process of developing a chrome extension using the node module "chrome-extension-async" and have encountered an issue with utilizing await within the background listener. In my setup, the content.js file sends a message to the ba ...