在博客应用中,我想在posts
的循环中显示/隐藏每个帖子的评论。我知道如何通过动态设置showComments
来显示包含注释的div:
this.$set(post, 'showComments', true) ;
但是当div已经打开时,我不知道如何隐藏帖子的评论。我试过的是这个
if (this.$get(post, 'showComments')==true) {
this.$set(post, 'showComments', false) ;
return
}
上面的代码不起作用,并且出现此错误:
Uncaught TypeError: this.$get is not a function
所以我想知道如何实现此功能。
答案 0 :(得分:2)
您应该能够简单地读取动态属性并重新应用该值。
new Vue({
el: '#app',
data() {
return {
posts: [
{ content: 'Post #1' },
{ content: 'Post #2' },
{ content: 'Post #3' }
]
}
},
methods: {
toggleComment(post) {
if ('showComment' in post) {
post.showComment = !post.showComment;
}
else {
this.$set(post, 'showComment', true);
}
}
}
})
.post {
background-color: lightgreen;
margin: 10px 0;
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="post" v-for="(post, index) in posts" :key="index">
{{post.content}}
<p v-if="post.showComment">
Hidden comments.
</p>
<button @click="toggleComment(post)">Toggle comment</button>
</div>
</div>
答案 1 :(得分:0)
使用属性名称获取属性值
procedure TForm1.DynamicMenuButtonClick(Sender: TObject);
var
categoryButtons: TCategoryButtons;
begin
categoryButtons := (Sender as TCategoryButtons);
Memo1.Lines.Add(categoryButtons.SelectedItem.Caption);
end;
还请注意,由于与其他库的冲突而已不推荐使用if ( typeof this.post.showComments !== 'undefined' && this.post.showComments ) {
Vue.set(post, 'showComments', false);
return;
}
,因此应尽量避免使用。考虑改用this.$set
。