Search code examples
vue.jsv-forv-model

Vue.js—V-model in v-for current object


Basically I would like when I create several pages to allow the v-model to take the input used and not all at once here is the code :

 <div id="app">
    <div class="container">
        <div class="row">
            <p class="jumbotron"> Titre de la page <input type="text" v-model="titre" > 
  <button type="submit"  v-on:click="ajouter()">Ajouter</button> </p>
        </div>
        <div class="row">
            <div class="row-5" v-for="(titre,index) in titres">
               
                    <p class="list-group-item" style="text-align: center;">
                        Titre de la page : {{ titre }}
                       <input type="text" value="" v-model="titremodify" ><br>
                        <button class="btn btn-dark" v- 
 on:click="supprimer()">Supprimer</button>
                    <button class="btn btn-dark" v- 
  on:click="modifier(index)">Modifier</button>
                    </p>
                </div>        
            </div>
    </div>
  </div>

https://jsfiddle.net/nestea29950/L8foc7zd/4/


Solution

  • The only thing you need to to is to add titre before your definition(s).

    TEMPLATE:

    ...
      <button @click="ajouter()">Ajouter</button>
    ...
      <div v-for="(titre,index) in titres" :key="titre.id">
        <input v-model="titre.titremodify">
      </div>
    ...
    

    SCRIPT:

    data() {
      return {
        titres: [{    //this is your first input
          id: 1,
        }]
        titremodify: "", 
      }
    }
    
    methods: {
      ajouter: function(){   
        this.titres.push({
          id: this.id +=1
        }); 
      },
    }
    

    For every titres in your v-for you create a titre with a unique ID (this will help you out in future matters). So you just have to reference on this like above.

    This should solve your problem.