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

Retrieve the updated text content from a textarea using JavaScript/jQuery

For a beginner in javascript and jquery like me, I encountered an issue with a textarea element that has preset content. When I change the value on the site to "new" and click the "showme" button, the alert box displays the preset value instead of the new ...

AngularJS application is throwing an error indicating provider $q is not recognized

Could someone please advise on what might be the issue with my code snippet below: var app = angular.module('app', [ 'angular-cache', 'angular-loading-bar', 'ngAnimate', 'ngCookies', &a ...

Tips for achieving a stable Vuetify configuration

Working on a project using vue 2 and vuetify, initially everything was going smoothly. However, after some usage, I encountered the following error: Module not found: Error: Can't resolve 'vuetify/src/stylus/app.styl' in '/Users/marce ...

Incorporate a fresh key-value pair into the Redux Toolkit's state

I am currently working on an application that enables users to create and modify recipes. To manage the state, I have chosen to utilize React Toolkit and Redux. Here is an example of the state structure: const ingredients = [ { ingredientName: &apos ...

Tips for setting up a Vue.js property as an array type element

To begin, I am looking to initialize the properties of image, description, video, and title with the corresponding fields from the first element in the variants array. The variants array is retrieved by sending an AJAX request that returns a JSON file. ...

"Enhance user experience with a multi-level dropdown menu feature in Bootstrap

I have been utilizing bootstrap-vue and I am trying to implement a multi-level dropdown menu for different categories. You can check out the official example on their website: <b-dropdown id="dropdown-1" text="Dropdown Button" clas ...

Issue with a stationary directional light tracking the movement of a rotating object and/or changes in the camera perspective

I've been facing a challenge in implementing a day-night cycle with a directional light in an Earth model using custom shaders. Everything seems to work fine with the night and day maps, as well as the light, as long as I don't manipulate the cam ...

At the onset, Vuex retrieves data from an API call

Excuse my lack of experience, I am fairly new to Vue/Nuxt/Vuex. Currently, I have a vuex store and I want to populate the list with data from an API call at the beginning so that I can access it directly from the store on all pages of my app rather than i ...

Tips for incorporating a User ID object into an Ajax request

Currently, I am delving into the world of web development and tackling a client-server project that involves allowing users to authenticate themselves and store their blood pressure readings. While the authentication part is functioning properly, I am enco ...

javascript to retrieve data by reducing

Here is the code snippet I am working with: var points = 4; var yModifier = []; for (var i = 0; i <= points; i++) { yModifier.push([]); }; yModifier.forEach( (a, j) => { var start = j; var end = start + points; fo ...

The target for CountUp is not defined in React.js and is either null or undefined

I'm experiencing an issue with React.js while using the CountUp library. I've tried everything I can think of, but so far, nothing has worked. I even created a state to check if the component is ready to render CountUp. I'm unsure whether t ...

Incorporating customizable data in Tailwind CSS 3 with Vue 3

Creating a dynamic arbitrary string in TailwindCSS, such as hue-rotate-[${randomHueColor}deg], is not feasible because the string needs to exist at build time. Even passing the generated string through a prop to a different component seems implausible. F ...

Error message in node.bcrypt.js: 'No callback function provided; result is undefined.'

Currently, I am enrolled in Mosh Hamdani's Mastering React Course and have encountered some challenges with back-end development. The most recent issue is an error message stating: “undefined No callback function was given” when attempting to regi ...

Encountering a Babel error while attempting to compile my front-end assets using Laravel Mix. The module build process fails, causing

I've been struggling to fix this persistent error, trying various solutions from different sources including Git, but nothing seems to work. Error: Module build failed: this.setDynamic is not a function In my package.json file, I have the following ...

What is the optimal approach for displaying numerous button components with varying values?

I've been developing a calculator in React and I decided to render all the buttons using the Button Panel component with what some might call a "brute force" method. return ( <> <div> <Button value="A/C" cl ...

Book Roulette: Your Next Random Read

I created a code for a random quote generator and now I want to create something similar, but with images this time. I am looking to add a feature on my page where it can recommend a book by displaying its cover image when a button is clicked. For the pre ...

When using iOS, the video compressing process stops automatically if the screen is no longer active while the file input

I am working on a web application that includes a file upload feature for large videos, typically 30 minutes or longer in duration. When a user on an iOS device selects a video to upload, the operating system will automatically compress it before triggerin ...

Unable to physically tap on the checkbox input, though able to perceive the value it holds

When running my protractor test, I encountered an issue with the following statement: await element(by.model('publishCtrl.isPublishedInAllRegions')).click(); The test failed and returned an error message stating "ElementNotVisibleError: element ...

What is the functionality behind a free hosting website?

Is anyone familiar with websites like Hostinghood, where users can create a subdomain and upload HTML, CSS, etc.? I'm curious about how they operate and how I can create a similar site. This is my first question here, so please respond instead of disl ...

View the selected radio buttons and checkboxes next to each other in real-time before finalizing and submitting

Within my form, individuals have the option to select from radio buttons and checkboxes. The challenge is that I need to display the chosen data on the page before they enter their email and submit! Since I cannot refresh the page, PHP won't work for ...