What is the best way to implement a multi-row form in Vue.js?

Form Structure:


    <card-wrapper
      v-for="(passenger, index) in form.passenger"
      :key="index"
      :icon="['fas', 'user']"
      :title="`Passenger ${index + 1}`"
      class="mb-5"
    >
      <validation-observer
        :ref="`passengerForm${index + 1}`"
        tag="div"
        class="row"
      >
        <b-col cols="12" class="mb-3">
          <b-row>
            <b-col lg="4" cols="12">
              <validation-provider
                v-slot="{ errors }"
                rules="required"
                name="First name"
                tag="div"
              >
                <form-text
                  id="first-name"
                  v-model="passenger.first_name"
                  :icon="['fas', 'user']"
                  :errors="errors[0]"
                  placeholder="First name"
                  tabindex="0"
                  class="mb-4"
                />
              </validation-provider>
            </b-col>

            <b-col lg="4" cols="12">
              <validation-provider
                v-slot="{ errors }"
                rules="required"
                name="Last name"
                tag="div"
              >
                <form-text
                  id="last-name"
                  v-model="passenger.last_name"
                  :icon="['fas', 'user']"
                  :errors="errors[0]"
                  placeholder="Last name"
                  tabindex="0"
                  class="mb-4"
                />
              </validation-provider>
            </b-col>
....

Form Data:


      form: {
        type: 'InvitationLetter',
        status: 'real',
        code: '',
        price: 18,
        gender: '',
        firstName: '',
        lastName: '',
        email: '',
        phone: '',
        destination1: '',
        destination2: '',
        social_media: [],
        options: [],
        passenger: [
          {
            gender: '',
            first_name: '',
            last_name: '',
            nationality: '',
            birth_date: '',
            passport_expiry_date: '',
            passport_number: '',
            travel_insurance: ''
          }
        ]
      }

The form functionality works fine until editing the data fetched from the server triggers the following error message:

[vuex] do not mutate vuex store state outside mutation handlers.

The page component fetches data like this:

pages/invitation-letter/_id.vue


  async fetch({ params, store }) {
    const PARAM = params.id
    if (PARAM) {
      await store.dispatch('invitationLetter/fetch', PARAM)
    }
  }

The form data is set in the form component as demonstrated below:


 computed: {
    ...mapGetters({
      result: 'invitationLetter/getData'
    }),
  created() {
    Object.keys(this.result).length !== 0 && this.setFormData()
  },
  methods: {
   setFormData() {
      this.count = this.result.passenger.length

      const NAME = this.result.name.split('-')
      const KEYS = Object.keys(this.form)

      KEYS.forEach((item) => {
        if (item !== 'firstName' && item !== 'lastName') {
          this.form[item] = this.result[item] ? this.result[item] : ''
        }

        ;[this.form.firstName, this.form.lastName] = [NAME[0], NAME[1]]
      })
    }
  }

While the form fields are populated correctly after fetching data from the server, any attempt to modify the data results in the same error message being displayed:

[vuex] do not mutate vuex store state outside mutation handlers.

This is how the form looks after fetching data from the server:

https://i.stack.imgur.com/b4GvW.png

Answer №1

It is advisable to avoid using the setFormData method as it may be unnecessary and could potentially cause errors. Instead, consider storing your form data in the store, retrieving it using a getter in the parent component where you utilize v-for, and updating its value in the store solely through mutations. Vue has built-in reactivity that will automatically update data in components.

For more information, refer to: Vuex getters Vue reactivity

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

Is it possible to incorporate a selection box along with the Raycaster in Three.js?

In my GLTF scene, I have been exploring the use of the example selection box (code) to select multiple meshes. Unfortunately, the current approach is providing inaccurate results as it selects based on the centroid of each mesh and includes meshes that ar ...

Is there a way for me to determine if a domain has been registered by the client?

I'm interested in creating a Web app that allows users to enter a domain name and then uses JavaScript to check its availability. I'm wondering if there's a method to do this without relying on my own hosting server. Is it possible to send a ...

What steps can I take to rearrange my return statement within an asynchronous function?

Imagine having a function that fetches data from a database. findById(id) { return Model.findById(id) } The goal is to rearrange the output from the user data in this format: { name: "Tom", age: 57 } To something like this: { message: ...

I would like to exclude the item within my ng-repeat loop using ng-if

I'm attempting to utilize ng-if within ng-repeat in order to create Accordions. Depending on the condition value, I want certain items to be skipped in the ng-repeat. For example, if item.condition is true, then only display the accordion. The code b ...

Looking to transfer zip files from a React user interface to a Node.js server backend, where I can then save the folder to a specific directory on my system

Frontend I am currently working on a feature that involves uploading a zipped folder containing CSV files from the React UI input field. import React, { useState } from "react"; import axios from "axios"; function App() { const [uplo ...

Volar and vue-tsc are producing conflicting TypeScript error messages

During the development of my project using Vite, Vue 3, and TypeScript, I have set up vue-tsc to run in watch mode. I am utilizing VS Code along with Volar. This setup has been helpful as it displays all TypeScript errors in the console as expected, but I ...

Using the keyof lookup in a Typescript interface is a powerful way to

I'm looking for a solution similar to: interface Operation<T, K extends keyof T> { key: keyof T; operation: 'add' | 'remove'; value: T[K]; } but without the necessity of passing K as a template. Essentially, I want to ...

Iterating through textboxes and buttons to trigger actions in JavaScript

Having an issue with JavaScript (or jQuery) where I can successfully input text and click a button on a page using the following script: document.getElementsByName('code')[0].value='ads0mx0'; document.getElementsByName('event&a ...

What are some tips for utilizing markers that display location values in the format of a bar chart on Google Maps?

Hey there, I have a project in mind to create a Google map with markers representing specific locations and their values displayed as bar charts. Here is the code snippet from my index page: --index.html-- <!DOCTYPE html> <html> <head ...

Transferring data between actions following an AJAX request in Zend Framework

I am currently utilizing an ajax call to communicate with a controller in order to update the number of articles displayed on the webpage. I have established an action within the controller to handle this ajax request. Below is a snippet of the code: publ ...

Ensuring thoroughness in validation without the use of specific text strings

Implementing the assignment or assertion of never at the end of a function is a strategy commonly used in Typescript to ensure exhaustive checks at compile time. To enable the compiler to recognize this, explicit strings are needed for it to check against ...

Angular tutorial: Organizing data by date only

This is my first time building an Angular app. I am fetching JSON data from an API using a factory service to get football match fixtures. My goal is to group these fixtures by date while disregarding the time component. The date string in the JSON is fo ...

The update feature seems to be malfunctioning within the MEAN Stack environment, specifically with node.js and angular js

Looking for some assistance as a beginner in the mean stack. I'm trying to update a record using the update function, but it's not working as expected. I need to update a specific object based on its ID, however, I'm encountering issues wit ...

What is the best way to create a drop-down menu that exports data directly to an Excel spreadsheet?

I have been struggling with a seemingly simple issue - I can't seem to get my drop-down box to display the chosen option. The code I'm using is quite similar to this generic one, but for some reason, it's not reporting the selected option to ...

Cannot display GIF file from the SRC directory in a React application

I am trying to display a gif from the "/src/images" folder in my component, but I keep getting my "old" value displayed instead. What could be causing this issue? Snippet from Danke.js site: import Confetti from "../images/confetti.gif"; <Box sx={{ ju ...

Issue with resetting the form field

Whenever a user opens a modal window to save data, I reset the form fields to blank. This works as expected, but I encountered an issue with AngularJS form validation messages appearing due to dirty check. I tried adding $setPristine() to resolve this, but ...

Steps for importing JQuery into a custom DNN module

I have developed a custom DNN module that requires the use of certain JQuery plugins. I successfully loaded the plugins, but encountered the following error: Uncaught TypeError: undefined is not a function imagesloaded.js?cdv=18:93 Uncaught TypeError: ...

Strategies for extracting special character codes from API data within a React functional component

I have been experimenting with a simple trivia API to improve my understanding of REACT. I have noticed that the question data is returning with special character codes, which is causing issues with react jsx. Can anyone suggest a method to easily convert ...

I'm having trouble with my useState in React/NEXTjs because it's not adding onto the result of a socket.io event from the server, it's simply

Frameworks used: Next.js, Socket.io, React I am currently working on a straightforward messaging application. The main concept involves emitting a message typed by a user, sending that message to the server, and then broadcasting it back to all clients th ...

Transfer the parameter from ajax function to the aspx.cs file

I've written some code using HTML, JS, and AJAX, but it's not functioning as expected. <script type="text/javascript"> function DeleteSelectedRecord(id) { alert(id); $.ajax({ type: "POST", ...