Merging Vue props with v-for for powerful data handling

Below is an example of my child component HTML:

<div v-for="(input, index) in form.inputs" :key="index">
  <div>
    <input :name"input.name" :type="input.type" />
  </div>
</div>

JavaScript (Vue):

<script>
  export default {
    name: "child",
    props: ['parentForm'],
    data() {
      return {
        form: {
          inputs: [
            {
              name: 'name',
              type: 'text'
          ],
          [...]
        }
      }
    }

Now, here's a sample of the root component HTML:

<child :parentsForm="form"></child>

JavaScript (Vue):

<script>
  import child from "./child";

  export default {
    name: "root",
    components: { child },
    data() {
      return {
        form: {
          data: {
            name: null,
            email: null,
            ...
          }
      }
    }

The question I have is regarding how to combine the root component with v-for loop.

I want to use the child component in this way:

<input :name"input.name" :type="input.type" v-model="parentForm.data . input.name" />

Since parentForm.data will bind form:data:{ and this will be the variable obtained from input.name

The output in v-model should be bound to form.data.name or form.data.email on the root component.

Thank you!

Answer №1

To implement this, you may use the following code:

<input :name="input.name" :type="input.type" v-model="parentForm.data[input.name]" />

By doing so, v-model will link parentForm.data.name with input.name = 'name'.

Answer №2

If I understand correctly, you are looking to update the data in a parent component from a child component. If so, there are two possible approaches.

  1. In the child component, you can use $parent.form.data for binding.
  2. Alternatively, you can pass the data down as a prop, assign it to a data property in the child component, bind this new data property within the child component, and then emit it whenever changes occur. Catch this emit in the parent component and update the parent property accordingly (Recommended).

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

Error: Trying to access 'whenReady' property of undefined variable is not allowed

As a beginner in electron app development, I am facing an issue when running npm start from the terminal. The error message I receive is: TypeError: Cannot read properties of undefined (reading 'whenReady')... This specific problem seems to be ...

Begin fetching data asynchronously in Vue Nuxt to initialize data

I'm working on a Vue-Nuxt component and I need to set the initial value of a data property in my component using data retrieved from an asyncData API call. data () { return { selected_company: this.contracts.company1.id *--> this gives me an ...

What is the process for configuring socket.io to solely listen on a single designated route?

Is there a way to make socket.io listen only on my /home route, instead of every route? I tried changing the configuration but it only displayed a JSON file on the home path. const server = require('http').Server(app); const io = require('s ...

A tool that enhances the visibility and readability of web languages such as HTML, PHP, and CSS

Looking to organize my own code examples, I need a way to display my code with syntax highlighting. Similar to how Symfony framework showcases it on their website: http://prntscr.com/bqrmzk. I'm wondering if there is a JavaScript framework that can a ...

Retrieve Gridview properties using JavaScript

I need to adjust the font size of my gridview using JavaScript to make it more suitable for printing. What is the best way to change the font size specifically for a gridview using JavaScript? ...

You cannot call this expression. The type 'String' does not have any call signatures. Error ts(2349)

Here is the User class I am working with: class User { private _email: string; public get email(): string { return this._email; } public set email(value: string) { this._email = value; } ...

Why is the ionChange/ngModelChange function being triggered from an ion-checkbox even though I did not specifically call it?

I have an issue with my code involving the ion-datetime and ion-check-box. I want it so that when a date is selected, the checkbox should automatically be set to false. Similarly, if the checkbox is clicked, the ion-datetime value should be cleared. Link ...

Ways to choose a Gmail account for logging into Firebase on mobile applications using Vue for a cross-platform application

Currently, I am developing a cross-platform app for iOS and Android that utilizes a .vue view to handle authentication via Gmail on Firebase. My approach involves using Google as the provider: provider = firebase.auth.GoogleAuthProvider() firebase.auth().s ...

Getting Rid of Angular Material Suggestions: A Step-by-Step Guide

<md-autocomplete ng-model="ctrl.searchText" md-selected-item="ctrl.selectedItem" md-selected-item-change="ctrl.selectedItemChange(item)" md-search-text="ctrl.searchText" md-search-text-change="ctrl.searchTextChange(ctrl.searchText)" ...

The Vue component is not displaying any data

Although Axios is successfully loading data, it's not displaying anything. Laravel Mix is also building without any errors. The code I have is as follows: index.html (body) <div id="app"> <posts></posts> </div> In app.j ...

While JSON Lint may declare the JSON data as valid, JSON.parse may still encounter an error when trying

I'm struggling to parse a simple JSON object. It's strange because when I check the validity of my JSON string on JSONLint (http://jsonlint.com/), it shows that it's valid. var data = '{"token":"9eebcdc435686459c0e0faac854997f3","email ...

Prevent the left border from displaying on a link that wraps to a new line

Excuse me, I am facing an issue with a pipe separator in my subnav bar between links. The problem is that the first link on a new line retains the left-border that should be disabled. How can I prevent this border from appearing on the first link of a new ...

I am encountering an issue with my function where I aim to prevent the creation of a node using duplicate coordinates

Trying to avoid creating a node with existing coordinates, I implemented a check in my code. The check is supposed to determine if there are any nodes with the same coordinates already present. However, it seems that the check is not working as expected an ...

Emphasize sections of text within a chart

Looking for a Specific Solution: I've encountered similar problems before, but this one has a unique twist. What I'm trying to achieve is to search for a substring within a table, highlight that substring, and hide all other rows (tr's) th ...

Getting parameter names (or retrieving arguments as an object) within a method decorator in TypeScript: What you need to know

I am currently working on creating a method decorator that logs the method name, its arguments, and result after execution. However, I want to implement a filter that allows me to choose which parameters are logged. Since the number and names of parameter ...

What techniques can be used to avoid blinking while forcefully scrolling to the left?

In my previous inquiry about dynamically adding and removing divs on scroll, I was unable to find a satisfactory solution among the responses provided. However, I decided to take matters into my own hands and attempted to implement it myself. My approach ...

How to link a CSS file from a JavaScript file

I have a form for users with fields for first name, last name, password, and confirm password. I've implemented validation to check if the password and confirm password fields match using JavaScript: $(document).ready(function() { $("#addUser").cl ...

Selecting the content within a table to easily edit it

I am working on a project where I have a table filled with data fetched from a database. My goal is to allow users to click on a cell in the table, make changes to its content, and then save those changes back to the database. Below is the code snippet I a ...

Exploring the functionality of ISO 8601 periods with JavaScript

Has anyone successfully compared ISO 8601 periods in JavaScript to determine which period has a longer duration? For example, is P6M (6 months) longer than PT10M (10 minutes)? I haven't been able to find any built-in solutions for this. Any suggestio ...

Tips for adjusting the material ui Popper width to fit the container without disabling the portal

Currently utilizing the material-ui popper library. I am trying to allow the popper to extend outside of its container in the vertical direction. To achieve this, I have set disableportal={false}. However, upon setting disableportal to false, when assign ...