What is the process for dynamically inserting a new object into an array of data objects in Vue.js?

I am a beginner with vue.js and currently working on a form. I have an add button in my form, so when the user clicks on it, the same form field will be added to the form. Users can add as many times as they want. Here is my initial data:

data () {
    return {
      form: [{
          fieldOne: '',
          fieldTwo: '',
      }]
    }
}

When the user clicks on the add button in HTML, my addForm function is triggered.

addForm() {
 let newObject = {
              fieldOne: '',
              fieldTwo: '',
          }
 this.form.push(newObject); // However, this gives me an error.
}

I have come across Vue.set, which allows adding single fields or objects easily. But I'm unsure about how to add an object to my form array.
Any assistance would be greatly appreciated.

Answer №1

It seems to be functioning fine. What specific issue are you encountering?

HTML Markup:

<div id="vueRoot">
  <button @click="addForm">
    Click Me !
  </button>
  {{form}}
</div>

Javascript Code:

var vm = new Vue({
  el : "#vueRoot",
  data : {
    form: [{
      fieldOne: '',
      fieldTwo: '',
    }]
  },
  methods : {
    addForm() {
      let newObject = {
        fieldOne: '',
        fieldTwo: ''
      }
      this.form.push(newObject); // Generates an error.
    }
  }
});

If you're just exploring and experimenting as a beginner, consider using descriptive names for variables. Using generic names like "form" and "fieldOne" can lead to confusion!

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 process of uploading a React App to Heroku resulted in a critical error: "FATAL ERROR: Heap limit reached, Allocation failed - JavaScript heap out of memory."

There's a puzzling issue that I believe I have the solution to (paying for more bandwidth on Heroku), but the root of the problem eludes me and it's truly frustrating. Any assistance in pinpointing the cause would be greatly appreciated! Hopefull ...

HTML anchor tag failing to redirect to specified link

I need to populate the URI property from an API result into an HTML format. I attempted to achieve this by calling a function and running a loop 3 times in order to display 3 links with the URI property of each object. However, the code is not functioning ...

A pair of buttons each displaying a unique div block

I am facing an issue with my jQuery script. I want to be able to click on one of the previewed text associated with a button and then have the other one close automatically. The desired effect is for the text to slide down using slideDown() and disappear ...

Stop jQuery function from activating twice during scrolling

I'm looking for a solution to optimize my code that detects if an element is in the viewport and triggers certain actions. Currently, it re-runs the code every time a scroll event occurs when the element is above the fold. Is there a way to make it on ...

The request included an unsupported media type of "text/plain;charset=UTF-8". This caused an error in the NextJS API when interacting with Django Rest Framework

Currently diving into the world of web development, I am endeavoring to construct a website utilizing NextJS and Django Rest Framework. While NextJS effectively proxies API endpoints for retrieving data, I find myself grappling with making it work for a PO ...

Verify FileReader.onload function using Jasmine and AngularJS

I have a unique directive specifically designed for uploading and importing binary files. This directive listens for a change event on an <input type="file"../> element. Currently, I am facing an issue with the code coverage of my test. Although the ...

Utilizing query parameters as variables in rewrites with Next.js

My goal is to use Next JS to redirect requests from /home?id=123qwert to the new path of /home/123qwert. I'm struggling with extracting the query parameter from the source and using it in the destination. This is what I have attempted so far: as ...

Dynamic resizing navigation with JQUERY

I have successfully created a navigation menu that dynamically resizes each list item to fit the entire width of the menu using JavaScript. $(function() { changeWidth(500); function changeWidth(menuWidth){ var menuItems = $('#menu l ...

Initially, calling angular.element(..).scope() will return undefined

I have encountered an issue where I am unable to access my angular controller's scope outside of the controller. This problem arises when using an external JavaScript library that performs certain actions and executes callbacks upon completion. In one ...

Tips on creating a unique d3js tree design

I am a beginner when it comes to d3js and javascript in general. My goal is to create an interactive IP administration overview using d3js by modeling json data. I know that the key tool for this job is likely d3.layout.tree, which will provide me with the ...

Adding Multiple Items to an Express Endpoint

I have a requirement to store multiple objects in my mongo database within an express route. Currently, the process is smooth when I post individual objects (such as ONE casino), as shown below. Instead of repeating this numerous times, I am seeking assist ...

I am attempting to incorporate an NPM package as a plugin in my Next.js application in order to prevent the occurrence of a "Module not found: Can't resolve 'child_process'" error

While I have developed nuxt apps in the past, I am new to next.js apps. In my current next.js project, I am encountering difficulties with implementing 'google-auth-library' within a component. Below is the code snippet for the troublesome compon ...

How can you append an object with a defined key to an array in Vue?

Currently developing a vue-application that includes a component for managing driving licenses. Here is an overview of my data setup: data() { return { custom_licenses: [], basic_licenses: [] } } Within my methods, I have the following l ...

Creating a seamless scrolling experience with a designated stopping point - here's how to achieve it!

I understand how to implement a scroll effect on an element with a specific class or ID. However, I am unsure of how to make the scrolling stop 20px above that element. I have seen examples using document.getElementById() to achieve this: function scr ...

Issue with accessing form in Angular 6 Reactive forms for custom validator functionality

I am facing an issue with creating a password validation for reactive forms in Angular. Every time I try to verify the password, I get a “Cannot read property 'get' of undefined” error in the console. I have tried different methods to access ...

How can I add header and footer elements in dot.js template engine?

My understanding was that all I needed to do (as per the documentation on GitHub) was to insert {{#def.loadfile('/snippet.txt')}} into my template like this: <!DOCTYPE html> <html> <head> <meta charset=&a ...

JavaScript drop-down menu malfunctioning

I am currently in the process of learning web development languages, and I'm attempting to create a dropdown list using JavaScript (I previously tried in CSS without success). I would greatly appreciate it if you could review my code and let me know ...

The offset value was inconsistent in the desktop version of Firefox

Could you take a look at my code on the fiddle link, Here is the code snippet: <body> <div id="content" style="width:400px; height:110px;"> <svg id="circle" height="300" width="300"> <circle cx="150" cy="150" r="40" st ...

Looking to retrieve a JavaScript code block from an AJAX response using jQuery?

How can I extract a Javascript code block from an ajax response using jQuery, while disregarding other tags (in this case, the div tag) and prevent the execution or evaluation of the Javascript code? Example in get_js.html: <script> $(function ...

Utilizing Cowboy as the HTTP web server for Express JS

Many websites are utilizing Cowboy as the HTTP Web server and Express JS as the Web application server. They typically have their HTTP header set to Cowboy for the server, with the X-Powered-By HTTP header indicating Express. One example is This setup rai ...