gpt4 book ai didi

javascript - 如何在 VueJS 中使类的 "virtual"getter 响应式

转载 作者:行者123 更新时间:2023-12-02 23:53:56 25 4
gpt4 key购买 nike

我有一个 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 getter 看起来像一个响应式属性。给定一个像这样的 vue...

<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 添加一个 compulated 方法,该方法调用 BlogPost 上的“getter”,但这似乎并未设置与评论集合的依赖关系。而且 Vue.set() 似乎没有提供帮助。我可以在哪里“设置”一些东西来让 vue 使用react?

我唯一的想法(我认为可行)是在评论集合上设置一个观察者,并让该观察者通过调用 comments getter 来更新数据中的其他值,但我可能会在同一对象和其他对象中存在数十种这样的情况。我想避免编写这么多的观察者并在数据中保留这么多额外的状态。有任何想法吗?谢谢/

最佳答案

这可能会有所帮助:

<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>

关于javascript - 如何在 VueJS 中使类的 "virtual"getter 响应式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55498623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com