Home » vue » How to handle different input values created with v-for

How to handle different input values created with v-for

Posted by: admin November 26, 2021 Leave a comment


I was wondering how to handle different input values when they have been created with v-for. In this example, let’s say I have some tweets from different users, each having their own reply field. How can I treat the input values as separate entities?

In this Fiddle, you can see the input values bind to the other input values. How could I pass the value of the selected field to the the reply method without the current binding side-effect? Thanks.

JS Fiddle: https://jsfiddle.net/n2fole00/n60d4qos/


<div id="app" style="margin:10px;">

  <div v-for="(tweet, key) in tweets">
    <p><strong>{{ tweet.user }} wrote...</strong></p>
    <p>{{ tweet.text }}</p>
    <label v-bind:for="'reply-'+key">Reply: </label>
    <input v-bind:id="'reply-'+key" v-model="replies" type="text">
    <button v-on:click="reply(replies, tweet.user)">Reply</button>



new Vue({
  el: "#app",
  data: {
    replies: [],
    tweets: [
      { text: "Learn JavaScript", user: "Bob" },
      { text: "Learn Vue", user: "Alice"},
      { text: "Play around in JSFiddle", user: "John" },

  methods: {
    reply(reply, user) {
      alert("You replied\n" + reply + "\nto " + user);

In a larger/production app, I would probably make each user field its own component (or two, one for the tweet and one for the reply, both orchestrated by this parent).

in this case, you can use the key as the array index for replies and get only the relevant information. See the updated fiddle.

in template:

<input v-bind:id="'reply-'+key" v-model="replies[key]" type="text">
<button v-on:click="reply(replies, tweet.user, key)">Reply</button>

in methods:

reply(reply, user, key) {
  alert("You replied\n" + reply[key] + "\nto " + user);