Oskar Mikael
Oskar Mikael

Reputation: 326

Vue JS Dynamic data and model in form input

I'm trying to create a form where users edit their comments. The input should display the current value of the comment (which is dynamic data coming from a v-for), but I also need to bind the value to a model so that I may send it with my patch request.

Currently the form looks like this

<p @click="editing = true">
     Edit comment
</p>
<form v-if="editing" @submit.prevent="editComment(comment._id)">
   <input type="text" v-model="comment.message"/>
   <button type="submit">
     Edit Comment
   </button>
 </form>

Would there be any way to combine the v-model and :value binding? Or a way to bind the model value aswell and setting the name of the data?

Upvotes: 1

Views: 1602

Answers (1)

tho-masn
tho-masn

Reputation: 1174

Assuming every comment is rendered within it's own comment, this would be an approach you can use (not tested):

Parent component:

<template>
  <div>
    <Comment 
      v-for="comment in comments"
      :key="comment._id"
      :comment="comment"
      @on-update="onUpdateComment"
    />
  </div>
</template>

<script>
  export default {
    data () {
      return {
        comments: [] // Could be also a computed property, or you populate the array somewhere in this component
      }
    },

    methods: {
      onUpdateComment({ commentId, value }) {
        // Perform update
      }
    }
  }
</script>

Child component (Comment):

<template>
  <div>
    {{ comment.message }}

    <p @click="onClickEdit">
        Edit comment
    </p>

    <form v-if="editing" @submit.prevent="editComment">
      <input type="text" :value="updatedCommentMessage"/>

      <button type="submit">
        Edit Comment
      </button>
    </form>
  </div>
</template>

<script>
  export default {
    props: {
      comment: {
        type: Object
      }
    },

    data () {
      return {
        editing: false,
        updatedCommentMessage: ''
      }
    }

    methods: {
      onClickEdit () {
        this.editing = true
        this.updatedCommentMessage = this.comment.message
      },

      editComment () {
        this.$emit('on-update', { commentId: this.comment.id, value: this.updatedCommentMessage})
      }
    }
  }
</script>

The benefit of storing the message bound to the input in it's own variable is, that you easily can cancel the action, by just resetting the updatedCommentMessage variable.

Upvotes: 1

Related Questions