Dynamically add Vuejs/Laravel inputs

Asked

Viewed 496 times

0

I’m learning how to work with Vue.js, and I need something relatively simple but I couldn’t solve, generate inputs dynamically in a form. Basically the form already comes with an input, and whenever you click the add button you have to add one more input, can help me?

<template>
    <form method="POST" action="">
        <div class="name">
            <h5><b>Nome da Seção: </b></h5>
            <input type="text" class="form-control" id="nome" placeholder="Digite aqui o nome da seção">
        </div>
    <hr>
    <div id="idDiv">   
        <h5>Digite os Itens:</h5>     
        <input type="text" class="form-control" id="item" placeholder="Digite o nome do Item" style="max-width:300px;">        
    </div>
    <hr>
    <div class="submit">
        <button class="btn btn-outline-secondary" type="button" style="min-width:150px;">Adicionar</button>
        <button class="btn btn-outline-secondary" type="button" style="min-width:150px;">Enviar</button>
    </div>
</form>
</template>
<script>
    export default {

}
</script>
  • Luiz maybe something like that? https://codesandbox.io/s/goofy-river-0o18k?file=/src/App.See This part of the documentation: https://br.vuejs.org/v2/guide/list.html

  • thank you very much

  • @Could Joséeduardokimura copy this code for the answer (and the link)? only the link is little to answer, but your solution is good and would give a good answer for me +1 ;)

1 answer

1

the following, let’s create a new method data which returns objects within the current component, within data create an 'counter', in the example I gave the same input name, input will start with the value 1.

export default {
  data: () => {
      return {
        input: 1
       }
  }
}

In the part of the 'Add' button we will define an event handler that will interact with the previously defined input counter. It works like this, every click on the button will be added to the counter 'input' plus a unit.

<button @click="input++" class="btn btn-outline-secondary" type="button" style="min-width:150px;">Adicionar</button>

In Input we will use the v-for to render in html the amount of input based on the 'input' contactor that we defined earlier.

<input v-for="i in input" :key="i" type="text" class="form-control" :id='"item"+i' :placeholder="'Digite o nome do Item '+i" style="max-width:300px; margin-top:5px"> 

Note that I used a bind on id input to dynamically generate a new id to each new input added to our counter, the id for each input will look like this 'item' + valor do contador. Example 'item1', 'item2', 'item3.... inserir a descrição da imagem aqui

You can understand more of v-for here https://br.vuejs.org/v2/guide/list.html

Event handlers here https://br.vuejs.org/v2/guide/events.html

Data and methods here https://br.vuejs.org/v2/guide/instance.html#Data-e-Metodos

Browser other questions tagged

You are not signed in. Login or sign up in order to post.