Dynamic Vue2 input field names

With Vue2, I am attempting to create input tags with dynamic content. My attempts at binding it to a function using :name="someFunction" have been unsuccessful in this case. The name attribute needs to be in the format

people[0]['name']
people[1]['name']

The numeric value should correspond with the key value of the loop over people. While I typically rely on ajax/axios requests based on the stored model, that approach is not feasible this time.

Below is a snippet of my current setup:

new Vue({

  el : '#example', 
  
  data : { 
    
    people : [
       {
          name : 'Tom',
          age : 12
        },
        
        {
          name : 'Susan',
          age : 18
        },
    ]
    
  } 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="example">

<div v-for="(person,key) in people">

  <input type="text" name="people[key]['name']" :value="person.name">
  
  <!-- The name should be dynamic people[0]['name'] -->
  <!-- and people[1]['name'] -->
</div>

</div>

Thank you for your assistance!

Answer №1

If you use v-bind (or the shorthand :) and change name to :name, you can assign any JavaScript expression as its value.

For instance:

:name="'people[' + key + '][\'name\']'"

Take note that the attribute's value is essentially a JavaScript expression:

'people[' + key + '][\'name\']'

This involves string concatenation with the variable key and another string.

See the demo below:

new Vue({

  el : '#example', 
  
  data : { 
    
    people : [
       {
          name : 'Tom',
          age : 12
        },
        
        {
          name : 'Susan',
          age : 18
        },
    ]
    
  } 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="example">

<div v-for="(person,key) in people">

  <input type="text" :name="'people[' + key + '][\'name\']'" :value="person.name">
  
  <!-- The name should be dynamic people[0]['name'] -->
  <!-- and people[1]['name'] -->
</div>

</div>

Answer №2

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="example">

<div v-for="(person,index) in people" :key="index">

       <input type="text" :name="`people[${index}][${person.name}]`" :value="person.name">
  
  <!-- Make sure to add a binding key ":key=your_index" for clarity -->
  <!-- Replace the parameter name key with index for better understanding -->
</div>

</div>

i believe adding the ":key=your_index" binding key and replacing the parameter name key with index will make the code clearer and more meaningful.

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

How to flip the value in v-model using VueJS

Below is the code snippet that I am working with: <input v-model="comb.inactive" type="checkbox" @click="setInactive(comb.id_base_product_combination)" > I am looking to apply the opposite value of comb.inactive to the v-model. Here are m ...

The $scope object in Angular is supposed to display the $scope.data, but for some reason, when I attempt to access it

Having an issue with my controller that fetches data from a service. After receiving the data in the controller, I'm using $scope to pass it to the view. Strange behavior - console.logs inside the 'then' function display the data correctly ...

Freezing objects using Object.freeze and utilizing array notation within objects

Could someone kindly explain to me how this function operates? Does [taskTypes.wind.printer_3d] serve as a method for defining an object's property? Is ["windFarm"] considered an array containing just one item? Deciphering another person& ...

Can Firebase lists be reversed?

I have searched extensively on SO for an answer to this question, but I haven't found a solution yet. Therefore, please do not mark this as a duplicate. Currently, I am working with AngularFire in Angular 2 and Typescript. I am using FirebaseListObse ...

Is it really necessary to import React from 'react' in the index.js file when importing react is no longer required?

Currently diving into the world of React.js. I recently found out that after version 17, importing React is no longer necessary. My current React version is v18.2.0. Here's the code snippet in question: // import React from 'react'; import ...

In the following command, where is the PORT stored: ~PORT=8080 npm App.js?

section: Let's consider the following code snippet located in the App.js file: console.log(`This is the port ${process.env.PORT}`); Is there a method to retrieve the value of PORT from outside the running process? ...

What is the best way to incorporate white-space:normal within the text of a jQuery Mobile grid button?

Below is the code for my jQuery Mobile Grid buttons: <div class="ui-grid-b my-breakpoint"> <div class="ui-block-a"><button type="button" data-theme="c"> <img src="res/icon/android/business.png" height="45"><br>Business</ ...

When incorporating Vue as an npm package, a Vue 3 app may inadvertently clear the mounted element upon initialization

I have a straightforward Vue 3 application that is working perfectly fine when I include Vue as a script, as shown in the code snippet below. However, I need to integrate it with webpack by including it as an npm package. When I do this, the app loads but ...

"Apple TV now features an iOS app that allows users to watch YouTube videos

I am interested in developing an iOS application that can play YouTube videos in a UIWebView window. Users should have the option to play the videos directly on their iOS device or stream them via AirPlay to an AppleTV. The content displayed in the UIWebV ...

The Fetch API's Post functionality is currently experiencing issues

fetch('http://localhost:9000/api/app/contact', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: this.state.email, contactNumber: ...

What is the best way to filter out and combine one array from two arrays in lodash based on their unique properties?

Lodash v 4.17.15 Consider the scenario where two arrays are involved: var users = [{ id: 12, name: Adam },{ id: 14, name: Bob },{ id: 16, name: Charlie },{ id: 18, name: David } ] var jobs = [ ...

Utilizing CDN script with Shopify: A guide to optimization

I am currently utilizing VueJs in the development of a Shopify theme using Shopify Cli and Store 2.0. To incorporate Vue, I initially attempted to install it through a CDN script within my theme.liquid file. <script src="{{ 'vue.global.js&apos ...

Adjusting the font color when hovering over multiline text

I am currently in the process of coding a website for my job, and I am working on changing the text color when it is hovered over. However, there seems to be a break in my code causing the text not to highlight all at once. Any guidance or suggestions on h ...

How to trigger a function in a separate component (Comp2) from the HTML of Comp1 using Angular 2

--- Component 1--------------- <div> <li><a href="#" (click)="getFactsCount()"> Instance 2 </a></li> However, the getFactsCount() function is located in another component. I am considering utilizing @output/emitter or some o ...

Is it possible to have scope inherit from an object in AngularJS?

Imagine creating an app like this: <script> myArray=<?php echo $array;?>; app={ myArray:myArray, myIndex:myArray.length-1, back:function(){this.myIndex--;console.log("You clicked back");}, forward:function(){this.myIndex++} } ...

Compiling TypeScript into JavaScript with AngularJS 2.0

Exploring the capabilities of AngularJS 2.0 in my own version of Reddit, I've put together a script called app.ts ///<reference path="typings/angular2/angular2.d.ts" /> import { Component, View, bootstrap, } from "angular2/angular2 ...

What is the best way to align a box once another one has been placed?

I have integrated both Bootstrap and Masonry plugins into my website design. The issue I am facing is that the Masonry plugin box goes under the top Bootstrap bar. I tried adding a margin-top: 50, but this resulted in a horizontal scroll bar appearing. To ...

What is the best way to display the next and restart buttons at the bottom of every question?

How can I display the next and restart buttons at the bottom of each question in my JavaScript quiz web app? Why is the user unable to choose the wrong answer from the provided options? I'm facing difficulty showing the next and restart buttons for i ...

`Finding and including the additional object in JavaScript`

Seeking guidance on how to manipulate a specific object in Javascript, I have successfully retrieved the object based on a filter, but I am unsure how to append `'in'='bank' and 'out'='bank'` of non-filtered ids to ...

Determine the exact moment at which the value shifts within the table

Looking for assistance in automating the grade calculation process whenever there is a change in table values. Any suggestions on how to achieve this? I am new to events and AJAX, so any help would be appreciated as I am still learning. Please see the ima ...