The act of appending values to an array within a hash in Vue is not functioning as expected

I am currently working on implementing a feature that allows users to add multiple workers by clicking the "Add worker" button. However, I have encountered an issue where placing the workers array inside the management object prevents this feature from functioning properly. The desired setup is to have the workers array within the management object, but doing so results in an error message stating "cannot read the property push".

<div v-for="(worker, index) in management.workers" :key="index">
  <v-container fluid>
    <v-layout row wrap>
      <v-flex xs12 md6 class="add-col-padding-right info-align">
        <v-text-field
           label='Name'
           v-model="worker.name"
           >
        </v-text-field>
      </v-flex>
      <v-flex xs12 md6 class="add-col-padding-left info-align">
        <v-text-field
           label='Hours of work'
           v-model="worker.hours_of_work"
           >
        </v-text-field>
      </v-flex>
   </v-layout>
   <v-btn class="red-button next-btn" @click="deleteRow(index)">Delete</v-btn>
 </v-container>                 
</div> 
<v-btn class="red-button next-btn" @click="addRow">Add Workers</v-btn>


<script>

export default {
  data () {
    return {
      management: {
        workers: []
      }
    }
  },
 methods: {
    addRow() {

      this.management.workers.push({
        name: '',
        hours_of_work: '',
        total: ''
      })
    },
    deleteRow(index) {
      this.management.workers.splice(index,1)
    }
  }
}
</script>

Answer №1

Here is the functional code snippet:

new Vue({
  el: "#app",
  vuetify: new Vuetify(),
  data() {
    return {
      management: {
        workers: []
      }
    }
  },
  methods: {
    addRow() {
      this.management.workers.push({
        name: '',
        hours_of_work: '',
        total: ''
      })
    },
    deleteRow(index) {
      this.management.workers.splice(index, 1)
    },
    getRows(){
      console.clear()
      console.log(this.management.workers)
    }
  }
});
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22444d4c5662160c5a">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="02747767766b647b42302c302c3032">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a3c3f2f0a786432">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c0a091908151a053c4e524e524e4c">[email protected]</a>/dist/vuetify.min.js"></script>
<div id="app">
  <v-app>
    <div v-for="(worker, index) in management.workers" :key="index">
      <v-container fluid>
        <v-layout row wrap>
          <v-flex xs12 md6 class="add-col-padding-right info-align">
            <v-text-field label='Name' v-model="worker.name">
            </v-text-field>
          </v-flex>
          <v-flex xs12 md6 class="add-col-padding-left info-align">
            <v-text-field label='Hours of work' v-model="worker.hours_of_work">
            </v-text-field>
          </v-flex>
        </v-layout>
        <v-btn class="red-button next-btn" @click="deleteRow(index)">Delete</v-btn>
      </v-container>
    </div>
    <v-btn class="red-button next-btn" @click="addRow">Add Workers</v-btn>
    <v-btn class="red-button next-btn" @click="getRows">View Workers</v-btn>
  </v-app>
</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

I am looking to add some flair to my ID "checkimg" using JavaScript

JavaScript if ((valid1 && valid2 && valid3 & valid4 && valid5 && valid6 && valid7 && valid8)==1) { // include an image in the specified ID. document.formElem.next1.disabled=false; } else { docume ...

What is the correct location for the webpack.config.js file within a React project?

I recently inherited a React project that I need to continue working on, but I have never used React before. I've been advised to use a web worker in the project and have found a tool that seems suitable for my needs: Worker Loader The suggested meth ...

Alert: Zone.js has identified that the ZoneAwarePromise '(window|global).Promise' has been replaced with polyfills. Kindly address this issue

Recently, I updated my Angular application from version 8 to 9. After updating the packages and successfully compiling the application, I encountered an error message in the Chrome browser console: Error: Zone.js has detected that ZoneAwarePromise `(wind ...

Tips for sending textarea data via AJAX with TinyMCE

Recently, I encountered an issue with submitting forms using the TinyMCE Jquery plugin. While regular input fields like text fields and select boxes submit just fine, there seems to be a glitch when it comes to submitting a textarea with TinyMCE. It requir ...

Switching the background image of a div when hovering over a particular list item

Here is my HTML: <li><a href=""><div class="arrow"></div>List Item</a></li> I'm looking to change the background image of the "arrow" class when hovering over the "List Item" with a mouse. The "arrow" class repres ...

Extending fabric.js toObject with custom properties can result in the loss of default properties

After doing extensive research on various platforms, including this one, I am still struggling to get everything working as desired. My main goal is to save custom properties in all shapes, specifically the uuid and rt_attributes. Following the manual, I ...

React state not being updated by setState method

Here's the situation: let total = newDealersDeckTotal.reduce(function(a, b) { return a + b; }, 0); console.log(total, 'tittal'); //displays correct total setTimeout(() => { this.setState({ dealersOverallTotal: total }); }, 10); cons ...

Issue encountered while serializing the `.product` object retrieved from the `getStaticProps` function in NextJS, in conjunction with

I ran into an error message saying "Error: Error serializing .product returned from getStaticProps in "/products/[id]". Reason: undefined cannot be serialized as JSON. Please use null or omit this value." This issue occurred while I was attempting to crea ...

unable to install npm package on Azure cloud platform

My attempt to deploy my website to Azure has hit a roadblock as npm install is failing with the following error: 2498 silly fetchPackageMetaData error for interactjs@git+https://github.com/taye/interact.js.git#v1.3.0-alpha.4 Command failed: D:\Prog ...

React and Axios: Overcoming CORS Policy to Connect with Java/SpringBoot REST Backend Service

As a first-time user of Axios to connect to my Java/SpringBoot Rest GET service on localhost:8080, I am using React and node.js. My goal is to successfully retrieve the REST data but encountered the following error: Failed to compile src\App.js Lin ...

What are the applications of global variables in node.js?

global.test = "test"; console.log(global.test); //test but I want to accomplish this: console.log(test); //test without using: var test = global.test; Is there a way to achieve this? I am looking for a solution where any module in my project does not ...

Looping through a dynamic array in Vue.js

I am working with two arrays: days:[0,1,2,3,4,5,6] and wdays:[2,3,6] My goal is to iterate through both arrays and display the output as follows: 0 : not present 1 : not present 2 : present 3 : present 4 : not present etc... The implementation should be ...

Obtain the JSON data from the body of the current post request in Express.js

I have been working on retrieving the actual request body JSON in express.js but haven't been successful so far. Most of the resources I found online only show how to access the body of type ReqBody, whereas I am looking for a way to retrieve the actu ...

Ways to organize JSON data from a fetch request into multiple divisions

I have written a JavaScript code to fetch JSON information. I plan on storing this JSON file locally (I downloaded an example file and added a birthdate object for my usage example from https://jsonplaceholder.typicode.com/users) My goal is to parse the r ...

What is the method for toggling background URLs?

Currently, I am utilizing flaunt.js by Todd Moto for my navigation system. My goal is to seamlessly switch the hamburger image with another image when the mobile-menu is shown and hidden. Check out the demo here. For a detailed tutorial, visit this link. ...

What are the steps to manipulate the data within an EJS file after passing an array through Node.js as an object?

I'm currently developing a simple calendar application using Node.js and ejs. I am working on passing an array of months through express to my ejs file, with the goal of being able to cycle through each month by clicking the next button. How can I imp ...

What is the method for showcasing background images sequentially?

css code #intro { position: relative; background-attachment: fixed; background-repeat: no-repeat; background-position: center top; -webkit-background-size: cover; -moz-background-size: cover; backgr ...

Using an Ajax XML object to dynamically set images in a DataList

When making an Ajax call to retrieve an XML response and trying to set image names from the XML on a datalist, I encountered some issues. The code snippet I used for setting the image is as follows: $(".Image", tablex).attr('src', product.find( ...

regex execution and testing exhibiting inconsistent behavior

The regex I am using has some named groups and it seems to match perfectly fine when tested in isolation, but for some reason, it does not work as expected within my running application environment. Below is the regex code that works everywhere except in ...

Local variable reference getting lost in a loop during a jQuery Ajax call

Currently, I am facing an issue with my jQuery ajax calls within a loop. The problem arises when each ajax call returns and I need to retrieve a specific value associated with the original call. However, due to further iterations in the loop, the value of ...