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

What is the best way to manage Page Refresh using Angular.js?

I recently followed the tutorial at http://scotch.io/bar-talk/setting-up-a-mean-stack-single-page-application This guide went over controllers and services using angular.js for a single-page application. However, when I try to directly access /pageName o ...

Switching components within the main view using VueJS Router with nested routes

The query How can I control a root-level view from a child route? The scenario is one level deep, but there may be situations where I need to control the other view from even deeper routes. Is it possible to have both the default view and another view ...

Customizing the date format in Vuetify's Datepicker

I am currently using a Vuetify Datepicker component in my project: <v-menu v-model="menu1" :close-on-content-click="false" max-width="290" > <template v-slot:activator="{ on }"> <v-text-field v-model="editedItem. ...

Puppeteer: Interacting with login dialog box fields

I am currently facing an issue while attempting to generate a .pdf file from a specific page on our Intranet using Puppeteer and Headless Chrome within Node.js. Generating a .pdf file from a regular webpage poses no challenge, but I am encountering diffic ...

Tips for displaying the updated value retrieved from an array

I'm struggling with displaying the values of an object. The table is supposed to show tasks and their remaining time to finish, but the countdown timer isn't updating. The values are stored in an Object by Task ID, like this: Object {1: "4017 D ...

Unable to access an element using jquery

This is an example of an HTML file: <div id ="main"> </div> Here is the JavaScript code: //creating a new div element var divElem = $('<div class="divText"></div>'); //creating an input element inside the div var i ...

Authentication through Proxy and requests from nodes

I am attempting to make a get request to a website via https using the request module. However, I am behind a proxy that requires authentication. Despite my attempts to add the authentication, the connection to the site fails. I have experimented with add ...

Changing the color of an open Bootstrap 4 accordion panel when the page loads

I am looking to emphasize the panel that the user has opened. If a user clicks the button in the card header, the background turns red, which is working smoothly as demonstrated in the code snippet. In certain scenarios, the first panel is open by default ...

Utilizing Cypress with Electron: A Guide to File System Operations

I have been utilizing Cypress to run tests on my Electron application. Due to Cypress operating in browser mode, the FS module is not compatible. As a result, I am encountering this error: Error in mounted hook: "TypeError: fs.existsSync is not a func ...

What steps are needed to build a Nested Default Dictionary in JavaScript?

I've been working on creating an Apps Script and have run into a challenge with implementing a Default Dictionary. Initially, I tried using the following code snippet: class DefaultDict { constructor(defaultInit) { return new Proxy({}, { g ...

What is causing the error message "TypeError: expressJwt is not a function" to appear? Is there a way to resolve it and fix the issue?

Authentication with JWT in Node.js: const expressJwt = require('express-jwt') function setupAuth() { const secret = process.env.SECRET_KEY return expressJwt({ secret, algorithms: ['HS256'] }) } module.expor ...

Using Axios with Django CSRF Token

Scenario: I am in the process of creating a full SPA using Vue.js for the front end and Django for the back end. These systems are completely separate, not a hybrid app where the index.html page is served by the back end. Strategy To facilitate communica ...

Tips for accessing <Field> values in redux-form version 7.0.0

class CustomForm extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { const { Add, noteList } = this.props; Add('this is title value' , 'this is ...

Tips for updating the content of multiple tabs in a container with just one tab in Bootstrap 4.x

I am attempting to create two tab containers, where one is used to describe the content of a set of files and the other is used as a list of download links for the described files. Initially, I tried controlling the two containers using just one tab. I ca ...

Occasionally, the system may mistakenly flag a password as invalid even though it is indeed correct

To ensure the password meets certain criteria, it must start with a Z, have at least 8 characters, and contain an asterisk *. Take a look at this validating function: function validatePassword() { var strPassword; //Prompt user to enter pas ...

Using the express.Router instance for handling errors can be a useful tool in your development

Based on the documentation, it states that any nodejs express middleware function has the capability of being swapped out by App or Router instances: Given that router and app adhere to the middleware interface, they can be used just like any other midd ...

Loss of precision occurs when converting a BigDecimal value from a JSON

After making a network call, the backend is sending the following data: "uom" : "EA", "qty" : 1.123456789012345678 However, when this information reaches the frontend and is logged using console.log: { qty: 1.1234567890123 ...

When combining CSS grids, nesting them can sometimes cause issues with the height layout

Check out the code on jsFiddle .component-container { width: 800px; height: 200px; background-color: lightyellow; border: 1px solid red; padding: 10px; overflow: hidden; } .component-container .grid-container-1 { display: grid; grid-tem ...

Default modal overlay closure malfunctioning; encountering errors when manually managed through jQuery

A custom overlay has been designed and implemented. <div class="overlay modal" id="11"> <div class="background-overlay"></div> <div class="description"> <div class="hidden-xs"> <img src=' ...

Extract the necessary fields from the JSON Schema

I am in search of a solution to extract the required fields from a JSON Schema and Data combination. Currently, we are utilizing AJV for getting error messages in our forms using JSON Schema, and it has been performing really well. I am looking for a met ...