Why isn't my Vue.js application automatically refreshing when I add or remove an object from the array?

In my Quasar and Vue.js project, I am working on a form where I can add objects to an array for insertion into the database simultaneously. However, I am facing an issue where the additions or deletions in the array only reflect on the screen after focusing on another input on the form. The manipulation of the objects in the array is happening correctly, but the changes are not immediately visible on the screen until I interact with another input element. Here's the code snippet:

<template>
  <form>
    <q-input
      v-model = "eventTitle"
      label = "Event title"
    />
    <div
      v-for = "(task, index) in tasks" :key = "index"
    >
      <q-btn
        label = "Remove Task"
        @click = "removeTask(index)"
      />
      <q-input
        v-model = "task.title"
        label = "Title"
      />
      <q-input
        v-model = "task.date"
        label = "Date"
      />
      <q-input
        v-model = "task.desc"
        label = "Description"
      />
    </div>

    <q-btn
      label = "Add Task"
      @click = "addTask"
    />
  </form>
</template>

<script>
  export default {
    setup () {

      const singleTask = {
       title: '',
       date: '',
       desc: ''
      }

      var tasks = []

      return {
        tasks,
        singleTask
      }
    },

    methods: {
      addTask() {
        this.tasks.push(this.singleTask)
      },

      removeTask(index) {
        this.tasks.splice(index, 1)
      }
    }
  }
</script>

Furthermore, editing one field in an object seems to affect others as well, presenting another challenge. If anyone has any suggestions or solutions to address these issues, I would greatly appreciate it as this is new territory for me.

Thank you in advance for your insights and responses.

Answer №1

There are several issues to address:

  1. singleTask is a single object instance, so pushing it into an array won't create a copy of the object. This means that your array contains multiple references to the same object. Research "JS value vs reference" for a better understanding of this concept.

  2. You are using setup, but the data structures returned from it are not reactive data. Make sure to use ref or reactive.

  3. Avoid using index as the key because it's essentially the same as not using a key at all. The key should be stable, meaning it should "connect" each object in the array to a DOM element created for it by Vue. Using index as a key isn't stable as it changes when items are deleted from the array.

Lastly, it's not recommended to mix the Composition API and Options API. It's best to stick with one or the other. Check out the new tutorial for more guidance.

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 click-handler method in VueJS Paginate Component fails to activate

I'm currently working on a Vue Component code that involves pagination for a list. The pagination seems to be working fine, except for the issue I encounter when trying to navigate to the next page, which in this case is page 2. I've added a cons ...

Having trouble running the npm run build command with vue-cli for production builds

Anticipated Outcome Executing npm run build should generate the production-ready dist bundle that can be deployed on a specified device. Current Scenario Despite successful local builds, encountering errors when attempting to execute npm run build on an ...

What could be the reason for the malfunction of the select (mongoose query)?

I'm trying to retrieve a User's highest score post. To accomplish this, I am querying the Post model and looking for posts where their user._id matches the author in the post. Everything is functioning correctly in this regard. However, my goal ...

Why does TypeScript keep throwing the "No inputs were found in the config file" error at me?

Why am I receiving the No inputs were found in config file error from TypeScript? I have set up my tsconfig.json in VS Code, but the error occurs when I try to build it. The terminal displays: error TS18003: No inputs were found in config file '/Use ...

Is fs-extra the best tool for working with a .bundle file?

I am attempting to determine whether a specific folder in my project includes a .bundle file and, if it does, relocate it to another location. If the file is not found, I will use a default option instead. The problem I'm encountering is that I am una ...

The property number will have no effect on the time

Currently, I am in the process of developing an audio player that includes essential functions such as backward, play, and forward buttons. Strangely enough, the backward function operates perfectly fine, but the forward button is not functioning properly ...

Display visual information without requiring the parameters to be filtered beforehand in vue.js

Upon opening my page, I encountered an issue where the graphics appear blank. This is because I set up the callback for generating graphic data through params request. I wish to first fetch the general data when the page opens, and only load with params w ...

jQuery is malfunctioning following an AJAX request

Can anyone help me fix an issue with my jQuery code? I have a hidden div that should be shown when the mouse hovers over a sibling element. However, it seems like after my AJAX function is executed, the jQuery stops working. <div class="parent"> ...

The update function in model.findByIdAndUpdate() is failing to make changes

I am struggling to update a user model with new data using findByIdAndUpdate(). Despite my efforts, the model does not reflect the changes made. Below is the code snippet where I am attempting to use findByIdAndUpdate() to add an object: const User = ...

Issue encountered with JavaScript function within TypeScript file connected to HTML code

I am currently working on a simple SharePoint web part and encountering an issue with using a function from another module file in my main file. Snippet from the JSFunctions.module.js file (where I define my function): function getApi(){ [my code]... }; ...

Exploring the possibilities of maximizing, minimizing, resizing, and creating a responsive design in dialog boxes using jQuery UI JavaScript and

I'm trying to create a dialog with maximize, resize, and minimize buttons like those found in Windows OS. I want the dialog to be responsive and draggable as well. I've been using jQuery, jQuery UI, and extended dialog frameworks, but I haven&apo ...

The constant issue persists with the NuxtJS store state variables continuously coming back as

I am facing an issue with the NuxtJs store where it keeps returning undefined. Even after looking at multiple similar questions, I haven't been able to find a solution. Here is my code snippet: import Vue from 'vue' import Vuex from 'vu ...

Sort with AngularJS: orderBy multiple fields, with just one in reverse

Currently, I am faced with the challenge of filtering data based on two variables: score and name (score first, followed by name). This task involves various games, some of which have scores in reverse order (like golf) while others maintain a normal scor ...

Having trouble with the installation of go get wails?

Attempting to implement golang and wails, but encountering issues after executing the following command: go get github.com/wailsapp/wails/cmd/wails Resulting in errors such as: ../../github.com/wailsapp/wails/cmd/semver.go:21:3: cannot use semverVers ...

Ways of retrieving Sveltekit session data in an endpoint

Is there a way to access a session in an endpoint using SvelteKit? I attempted the following with no success: import { get } from 'svelte/store'; import { getStores} from "$app/stores"; function getUser() { // <- execute this du ...

What could be causing my Ajax function to malfunction?

I've been attempting to incorporate a form that sends two javascript variables to a php script and displays the result in a new Div on the same page using an ajax function. Unfortunately, it's not functioning as expected. Here is the code snippe ...

Concerns have been raised regarding the lack of light and shadows being detected by THREE.BufferGeometry in JavaScript/th

I've been trying to generate terrain using noise functions, but I'm running into an issue where the BufferGeometry mesh isn't receiving any light from PointLight. When I switch to AmbientLight, the BufferGeometry is visible, but not with Poi ...

Is the parameter retrieval method correct or erroneous?

I am looking to retrieve data by clicking a link. Here are the links available: <a class="note" id="' . $data["p_id"] . '" value="1" href="javascript:void(0)">+1</a> <a class="note" id="' . $data["p_id"] . '" value="-1" ...

The SrollToTop function is ineffective when used with a component in Ionic 6/Angular

Recently, I implemented a fabbutton feature that allows users to scroll to the top of a page with just one click. Initially, I tested this functionality without using it as a component, and everything worked perfectly. However, now I want to turn this fabb ...

What is the best way to access an error's body in order to retrieve additional error message details when using the forge-api with nodejs?

I'm struggling to retrieve the body content when an error is returned from the API request. I've attempted creating a bucket with uppercase letters, but all I receive is an error object with statusCode = "400" and statusMessage = "BAD REQUEST". ...