Home > database >  Text input displayed dynamically in all the inputs in v-for
Text input displayed dynamically in all the inputs in v-for

Time:02-04

I have this piece of code :

 <post v-for="post in posts" :post="post" :key="post.id">
      <template v-slot:publishComment>
        <v-text-field v-model="message"></v-text-field>
        <v-btn color="green" type="submit" v-on:click.prevent="publishComment(post.id, message)">Go!</v-btn>
      </template> 
 </post>

with this code when I write a text in an input I see the same text displayed dynamically in all the inputs (created by v-for), although when I click Go!, only the right one is sent. So the question is how to make the entred text only appears in the right input. I thought of using a condition v-if with the focused input but I didn't manage to implement it.

CodePudding user response:

This is because all inputs have the same variable (message ) as v-model. Either create an array of messages or add it to post, like post. message.

CodePudding user response:

One observation : As you are creating inputs dynamically, v-model should be different for each input. In your sample code, you are binding same message to each input v-model which should be different for each input.

Working Demo :

const app = new Vue({
  el: '#app',
  data() {
    return {
      posts: [{
        id: 1,
        message: ''
      }, {
        id: 2,
        message: ''
      }, {
        id: 3,
        message: ''
      }]
    }
  },
  methods: {
    publishComment(id, message) {
        console.log('Id : ', id);
      console.log('Message : ', message);
    }
  }
})
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.0/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>

<div id="app">
  <div v-for="post in posts" :post="post" :key="post.id">
    <v-text-field v-model="post.message"></v-text-field>
    <v-btn color="green" type="submit" v-on:click.prevent="publishComment(post.id, post.message)">Go!</v-btn>
  </div>
</div>

  •  Tags:  
  • Related