There are two objects in my code, BlogPost and Comment, with the following structure:
class Comment {
constructor (blogId, text) {
this.blogId = id
this.text = text
}
}
class BlogPost {
constructor (id, text) {
this.id = id
this.text = text
}
get comments () {
return commentCollection.filter(comment => comment.blogId === this.id)
}
}
I am looking to make the comments
getter act as a reactive property. In the given vue setup...
<template>
<div>
<h1>The post has {{myBlogPost.comments.length}} comments</h1>
<v-btn @click="addComment()">Add Comment</v-btn>
</div>
</template>
<script>
export default {
data () {
return {
myBlogPost: null
}
},
methods: {
let newComment = new Comment('myBlogId_0', 'This is a comment on hello world')
commentCollection.splice(0, 0, newComment)
},
mounted () {
this.myBlogPost = new BlogPost('myBlogId_0', 'Hello World')
}
}
</script>
I want the comment count to update when a user adds a comment. How can I achieve this? Making the comment
collection of BlogPost reactive doesn't seem possible since it's not a propery.
I have tried using a computed
method in Vue that calls the "getter" on BlogPost, but it doesn't establish a dependency with the comments collection. Using Vue.set()
also didn't yield desired results. Where should I make changes to trigger reactivity in Vue?
The only solution I can think of involves setting up a watcher on the comments collection and updating another value in data by calling the comments
getter. However, this approach may become cumbersome if multiple similar situations arise within different objects. Is there a more efficient way to handle this without relying heavily on watchers and extra state in data? Thank you!