I'm getting a posts array from a vuex getter and looping through them with v-for to display each post and it's comment then i added an input field and binded it with v-model to get the input value and dispatch an action to send the value to the API

<div class="post-content"  v-for="(post, index) in posts">
   <div class="post-comment">
        <input type="text" class="form-control" placeholder="Add a comment" v-model="comment" @keyup.enter="addComment(post.id)">
   </div>
</div>
<script>
  export default {
    data() {
      return {
        postContent: '',
        comment: ''
      }
    },

    methods: {
      addPost() {
        this.$store.dispatch('addPost', {
          content: this.postContent
        })
        this.postContent = ''
      },
      addComment(postID, index) {
        this.$store.dispatch('addComment', {
          body: this.comment,
          post_id: postID
        })
      }
    },

    created(){
        this.$store.dispatch( 'loadFeed' )
    },

    computed: {
        postsLoadStatus(){
        return this.$store.getters.getPostsLoadStatus
        },

        posts(){
        return this.$store.getters.getFeed
        }
    },
  }
</script>

but when i set the v-model to a data property and try to type something in the input it's assigned on all posts so what's the right way to grab the comment data

1 Answers

0
Ohgodwhy On Best Solutions

Create a getter that accepts a function:

getters () {
   getCommentByPostId(state) => (post_id) => {
       return state.posts.find((post) => post.id === post_id).comment
   }
}

Then use that getter on that :value and not v-model:

<input type="text" class="form-control" placeholder="Add a comment" :value="$store.getters['getCommentByPostId'](post.id)" @keyup.enter="addComment(post.id)">

Make sure to handle scenarios where the comment doesn't exist and return an empty string, too.