skip to Main Content

I have this code in my vue app, it will create dynamic input fields

            <div class="col-sm-12 col-md-12 col-lg-12 mt-1 mb-1">
                <a class="text-uppercase text-decoration-none text-dark" href="#" @click.prevent="addField">
                    <i class="bi bi-plus"></i>
                    Add device properties
                </a>
            </div>
            <div class="col-sm-12 col-md-4 col-lg-4 mt-1 mb-1" v-for="inputs in fieldsCounter" :key="inputs">
                <div class="input-group">    
                    <input type="text" class="form-control text-uppercase rounded-0 me-1" v-model="deviceDetails.fieldName" placeholder="Field Name" @change="log">
                    <input type="text" class="form-control text-uppercase rounded-0 ms-1" v-model="deviceDetails.fieldValue" placeholder="Field Value" @change="log">
                </div>
            </div>

My method to create the fields is this:

 addField(){
   this.deviceDetails.push({})
 }

I need to create dynamic input fields but my problem is that I’m not able to get the v-model data of the new created fields. How I can solve this problem and create inputs corectly with a v-model assigned for each new input field??H

2

Answers


  1. Use v-for with v-model

    <div class="input-group" v-for="device in devices">    
         <input type="text" v-model="device.fieldName" placeholder="Field Name" @change="log">
         <input type="text" v-model="device.fieldValue" placeholder="Field Value" @change="log">
    </div>
    
    Login or Signup to reply.
  2. If I uderstood You correctly try like following snippet:

    const { reactive } = Vue
    const app = Vue.createApp({
      setup() {
        const deviceDetails = reactive([{}])
        const addField = () => {
          deviceDetails.push({})
        }
        return {
          deviceDetails, addField
        };
      },
    })
    app.mount('#demo')
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
    <div id="demo">
      <div>
        <a href="#" @click.prevent="addField">
          Add device properties
        </a>
      </div>
      {{deviceDetails}}
      <div v-for="inputs in deviceDetails" :key="inputs">
        <div>    
          <input type="text" v-model="inputs.fieldName" placeholder="Field Name" >
          <input type="text" v-model="inputs.fieldValue" placeholder="Field Value" >
        </div>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search