Vue 3 -在动态输入字段上使用v-model获取数据

oxf4rvwz  于 2023-04-21  发布在  Vue.js
关注(0)|答案(2)|浏览(247)

我在我的vue应用程序中有这样的代码,它将创建动态输入字段

<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>

我创建字段的方法是这样的:

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

我需要创建动态输入字段,但我的问题是,我不能得到新创建的字段的v模型数据。我如何解决这个问题,并为每个新输入字段分配一个v模型来正确地创建输入??H

wz3gfoph

wz3gfoph1#

v-forv-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>
bnlyeluc

bnlyeluc2#

如果我理解你正确的尝试像下面的片段:

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>

相关问题