我有一个BlogPost对象和一个Comment对象,它们大致如下所示:
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)
}
}
我希望comments
吸气剂看起来像是一种反应性。有了这样的主意...
<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>
...我想在用户添加评论时更新评论计数。怎么做?我不能使BlogPost
注释集合具有反应性,因为它实际上不是属性。
我曾尝试在Vue上添加一个computed
方法,该方法在BlogPost上调用“ getter”,但这似乎并没有建立注释集合的依赖关系。而且Vue.set()
似乎没有提供帮助。我在哪里可以“设置”某些东西以引起反应?
我唯一的想法(我认为会起作用)是在注释集合上设置观察程序,并通过调用comments
getter使该观察程序更新数据中的其他值,但是我可能有数十个这些情况在同一对象和其他对象中。我想避免编写太多观察者,并在数据中保留如此多的额外状态。有任何想法吗?谢谢/
答案 0 :(得分:1)
这可能会有所帮助:
<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: {
comments: []
}
}
},
methods: {
addComment() {
let newComment = new Comment('myBlogId_0', 'This is a comment on hello world')
// commentCollection is not defined in this snippet
commentCollection.splice(0, 0, newComment)
this.myBlogPost.comments.push( newComment )
}
// 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>