2

Using Vue2 I'm trying to create some input tags which have dynamic content. I have tried binding it to some function :name="someFunction" but that doesn't seem to work on this occasion. I need the name attribute to be in the format

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

With the number value being the key value of the loop over people. I usually create ajax/axios requests based on the stored model but on the occasion that method isn't possible.

Here is an example snippet of what I've got currently:

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>

Many thanks in advance

2 Answers 2

3

You can use v-bind (or its shorthand :) and make name into :name. This way, its value can be any JavaScript expression.

Example:

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

Notice the value of the attribute is actually the JavaScript expression:

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

Which is a string concatenated with the key variable, concatenated with another string.

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent - thank you! Had forgotten you could do it that way!
1

<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">
  
  <!-- The name should be dynamic people[0]['name'] -->
  <!-- and people[1]['name'] -->
</div>

</div>

i think you must add binding key ":key="your_index"" and replace your parameter name key with index, so that the meaning is clearer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.