Home > Enterprise >  Creating a name for v-model dynamically in Vuejs
Creating a name for v-model dynamically in Vuejs

Time:10-06

I have a button to create a new component 'AddressField' in each click. Inside this component I have a input that a I need to store the data inside the input;

Here is the button to activate the logic to create a new component

 <div >
      <button 
          type="button" 
           
          @click="addAddressField">Calculate
      </button>
</div>

Reusable component that is created in each click on the button above

<ul >
      <address-field
           v-for="(addressfield) in AddressFieldObject"
           :key="addressfield.id"
           :title="addressfield.title"
           v-model="?"
       ></address-field>
</ul>

Function to add a component

addAddressField() {

    this.AddressFieldObject.push({
          id: 'id'   this.nextAddressFieldID  ,
          title: 'title'   this.nextAddressFieldTitle  
         })
        this.newAddressField = ''
         }

Is there anyway to create a name for v-model dynamically? For example:

  • 1st click / component with v-model name 'nameModel01'
  • 2nd click / component with v-model name 'nameModel02'
  • 3rd click / component with v-model name 'nameModel03'

In the end, my objective is to store all the input inside a array or a object, just like:

  • array = [nameModel01, nameModel02, nameModel03]

CodePudding user response:

You need to use object.

I created an example

Pay attention on arr variable

CodePudding user response:

Could do like this.

<ul >
      <address-field
           v-for="(addressfield, index) in AddressFieldObject"
           :key="addressfield.id"
           :title="addressfield.title"
           v-model="nameModel[index]"
       ></address-field>
</ul>

or use addressfield.id instead of index.

  • Related