Home > Back-end >  Vue 3 - Create dynamic input
Vue 3 - Create dynamic input

Time:11-23

In the form I have a field to add the url of an image, but they can have several and I'm dynamically creating each input, but what I type in one changes in the other, where is the error?

Note: I found some tips but they didn't work either.

<script setup>
const items = ref([])
let ids = items.value.length   1

const addRow = () => {
  const i = Math.round(Math.random() * items.value.length)
  items.value.splice(i, 0, ids  )
}
<script>
<template>
<div>
        <InputLabel for="url" value="URL da imagem" />
        <div>
          <TextInput id="url" v-model="form.url" type="url" required />
            <button type="button" @click="addRow">
               
            </button>
        </div>
      </div>

      <div  v-for="(item, index) in items" :key="item">
        <InputLabel for="url" value="URL da imagem" />
        <div>
          <TextInput :id="index   1" v-model="form.url" type="url" required />
          <div >
              <button type="button" @click="addRow">
                 
              </button>
              <button type="button" @click="removeField">
                -
              </button>
          </div>
        </div>
      </div>
</div>
</template>

input image

CodePudding user response:

You can do this:

just change the label to your component and the input

<script setup>
  import { ref } from 'vue'
  const items = ref([
    {
      id:1, url: ''
    }
  ])
  const addRow = () => {
    items.value.push({
      id: items.value.length   1,
      url: '',
    })
  }
</script>

<template>
  <div>
    <div  v-for="(item) in items" :key="item">
      <label for="url" value="URL da imagem" />
      <div>
        <input :id="item.id" v-model="item.url" type="url" required />
        <div >
            <button type="button" @click="addRow">
               
            </button>
            <button v-if="item.id !=1" type="button" @click="removeField">
              -
            </button>
        </div>
      </div>
    </div>
  </div>
</template>
  • Related