Is it possible to use Vuejs v-model for a complete form instead of individual inputs?

Note: This solution is applicable for Vue 2.X

I am currently working on a unique Vue.js component that has the ability to generate "custom" forms.

This component essentially functions as a standalone form with multiple input fields. Users have the option to add questions, specify input types, and more within this dynamic form. All the data entered is then saved in an array structure, representing a complete form.

Looking ahead, this array of questions can be processed and utilized to display a fully functional form. This empowers users to construct their own forms without needing to hardcode them.

The issue at hand:

As previously mentioned, I intend to save all the data in an array format consisting of individual question objects. For instance, [ { 'question_name': "How are you", 'input_type': "text" }, ... ] and so forth.

However, because this form does not act as a single input field but rather comprises multiple smaller inputs, utilizing v-model on the form component directly becomes challenging.

Hence, there's no straightforward method to ensure that modifications made to the entire form data reflect in the parent component just like how changes in input fields linked with a v-model variable respond reactively.

For example, in my Parent.vue file, I would ideally wish for something like this:

<CustomFormComponent v-model="formData" /> # where formData represents the array mentioned earlier

allowing seamless communication between the parent and the form component, ensuring reactivity when formData undergoes alterations.

A viable approach, albeit not perfect:

One plausible solution involves implementing setter and getter methods within my custom form component. When data submission is required, the getter function can be invoked, while the setter can facilitate adding predefined questions whenever necessary.

If anyone has insights on whether achieving my desired functionality is feasible, your expertise would be greatly appreciated.

Answer №1

Not mentioning the specific version of VueJS being used can lead to confusion, so for this example let's assume it's VueJS 2. However, this code snippet can also be adapted for VueJS 3:

<template>
  <div id="app">
    <p>My Form</p>
    <CustomForm v-model="questions" />
  </div>
</template>

<script>
import CustomForm from "./components/CustomForm";

export default {
  name: "App",
  data() {
    return {
      questions: [
        { id: 1, label: "1", answer: "" },
        { id: 2, label: "2", answer: "" },
        { id: 3, label: "3", answer: "" },
        { id: 4, label: "4", answer: "" },
        { id: 5, label: "5", answer: "" },
      ],
    };
  },
  components: {
    CustomForm,
  },
};
</script>

Next is the CustomForm.vue component:

<template>
  <form>
    <div v-for="question in value" :key="question.id">
      <p>{{ question.label }}</p>
      <input
        :id="question.id"
        :value="question.answer"
        @input="(e) => (question.answer = e.target.value)"
      />
    </div>
  </form>
</template>

<script>
export default {
  name: "CustomForm",
  props: {
    value: Array,
  },
};
</script>

This setup can easily be extended to include other types of form elements such as select, checkbox, etc. It serves as a basic demonstration.

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

Vue alert: A duplicate key with the value of '10' has been identified. This could potentially lead to an issue with updates

I've been encountering a persistent error that I can't seem to resolve: [Vue warn]: Duplicate keys detected: '10'. This issue is causing an update error in my application. Despite trying the following steps, the error continues to appe ...

Navigating with Google Maps and Its Pointers

I've successfully integrated a JSON array of Marker positions into a Google map. Each marker has an associated infoWindow, which is also functioning as expected. However, I'm encountering an issue where clicking on a marker only displays the in ...

Is it possible to trigger the onNewRequest property when the onBlur event is fired for AutoComplete in Material-UI?

Currently, I am utilizing Material-UI and making use of the onNewRequest property in the AutoComplete field. However, the onNewRequest only triggers when Enter is pressed or when a value is selected. I am interested in calling the onNewRequest even when ...

Tips for Retrieving Data from a Multi-Dimensional Array

I need help accessing the values in my array and assigning them to variables for later use. I have created an array and used the randomGo() function to generate a random number that corresponds to a pair of numbers within the array. My goal is to assign ...

Are there specific files or classes that store constants for different keyboard events?

When working in Angular, I often bind data with a host listener using code similar to the example below: @HostListener('window:keyup', ['$event']) onKeyUp(event: KeyboardEvent) { if (event.keyCode === 13) { this.onEnterClicked(ev ...

Is it possible to effortlessly associate a personalized string with an identifier within an HTML element utilizing Angular2?

Check out this cool plunker import {Component} from 'angular2/core' @Component({ selector: 'my-app', template: ` <div *ngFor="#option of myHashMap"> <input type="radio" name="myRadio" id="{{generateId(option[& ...

Generating a header each time a table is printed across multiple pages

A table has been created in a webform using C#. The goal is to only print the table when the user clicks the print button on the webform. Javascript has been implemented in ASP.NET to only print the content within a specific div. While this method works, ...

Is your Ajax response suddenly failing to work after the initial attempt?

Describing my predicament: The code snippet below is what I have been using to insert a custom-designed div into my webpage. Initially, the div is successfully added; however, it stops working after the first instance. $('#addanother').click(fu ...

Implementing RXJS subscription using a Subject object

What is the benefit of using "Subscribe providing subject" and what does this entail: 1- The purpose of using subscribe providing subject import { Subject, from } from 'rxjs'; const newSubject = new Subject<number>(); newSubject.subscr ...

What is the best way to retrieve the axios baseUrl in nuxt?

In my Nuxt.js project, I have incorporated the axios module. The baseUrl for my API is set to 'localhost:4040/api', while my client is functioning on port 3000. However, when retrieving image data from the API, it outputs a relative path to the s ...

Error: The index "id" is not defined

Hey there, I have been working on fetching data from a JSON URL located at this link. However, I seem to be encountering an error that I can't quite comprehend. If anyone has any insights or solutions, I would greatly appreciate the help. Thank you in ...

Here's a unique version: "Strategies for effectively closing a modal when moving to a

I'm currently working with react-router-dom and material UI modal, and I am looking for a way to automatically hide the modal whenever the user navigates to another page. Here is my App component: const App = () => ( <BrowserRouter> &l ...

The domain retrieval is contingent on the language preference of the user

A task has been assigned to create a script in JavaScript/jQuery (or other suitable technologies) that will return a domain with a .pl extension if the user's browser language is set to Polish. Otherwise, the script should return a .eu domain extensio ...

Struggling to forward JSON data via AJAX to Django without relying on jQuery

My goal is to utilize AJAX in conjunction with Django, but I want to achieve this without relying on jQuery. So far, I have made progress in sending URL encoded data from AJAX to Django successfully. However, I am currently facing an issue where I am unabl ...

Use Vue and axios to retrieve images from imgur

When attempting to retrieve all images from the Galleries template, I encounter the error/warning message saying: "Property "token" was accessed during render but is not defined on instance". Instead of displaying the images, I see: <img src="function ...

Steps to create a toggle click event

I've been attempting to create a toggle click event using the code below: HTML <a class="load" data-gallery="123456" style="cursor: pointer;"><h2><p>example</p></h2></a> <div id="123456"> </div> j ...

JavaScript drag functionality is jerky on iPads, not seamless

I am currently attempting to implement a feature where I can drag a div (#drag) within its parent container (#container) using only pure JavaScript. This functionality is specifically required to work on iPad devices only. After writing a script that func ...

Incorporating an SVG with CSS styling from a stylesheet

After exploring various articles and questions on the topic, I am yet to find a definitive solution. I have an external file named icon.svg, and my objective is to utilize it across multiple HTML files with different fill colors and sizes for each instanc ...

Building upcoming records in Firestore

Seeking advice on the best approach for managing future milk orders in my Vue.js application. In this app, customers can subscribe to order milk 1, 2, or 7 times a week for a specific period (e.g. 90 days). The challenge lies in determining how to handle ...

Methods for organizing an array of objects by a specific key in JavaScript, but in the case of duplicate values, the objects can be sorted by a different

I'm struggling to sort an array of objects by two different keys. I need to first sort the array by price, and if there are multiple items with the same price, they should then be sorted by time. Here's what my array looks like: var myArr = [ {&q ...