Vue.js 中 $set 的反义词是什么? [英] What is the opposite of $set in Vue.js?

查看:32
本文介绍了Vue.js 中 $set 的反义词是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在博客应用中,我想显示/隐藏每个帖子的评论帖子的循环中.我知道如何通过动态设置 showComments 来显示包含评论的 div:

this.$set(post, 'showComments', true) ;

但是当div已经打开时我不知道如何隐藏帖子的评论.我试过的是这样的:

 if (this.$get(post, 'showComments')==true) {this.$set(post, 'showComments', false) ;返回}

上面的代码不起作用,我收到此错误:

未捕获的类型错误:this.$get 不是函数

所以我想知道我怎样才能实现这个功能.

解决方案

您应该能够简单地读取动态属性并重新应用该值.

new Vue({el: '#app',数据() {返回 {帖子: [{内容:'帖子#1'},{内容:'帖子#2'},{ 内容:'帖子 #3' }]}},方法: {切换评论(帖子){如果(帖子中的'showComment'){post.showComment = !post.showComment;}别的 {this.$set(post, 'showComment', true);}}}})

.post {背景颜色:浅绿色;边距:10px 0;填充:5px;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><div id="应用程序"><div class="post" v-for="(post, index) in posts" :key="index">{{post.content}}<p v-if="post.showComment">隐藏评论.</p><button @click="toggleComment(post)">切换评论</button>

In a blog app, I'd like to show/hide comments of each post inside a loop of posts. I know how to show the div containing the comments by setting a showComments on the fly:

this.$set(post, 'showComments', true) ;

But I don't know how to hide the post's comments when the div is already open. What I tried is this:

 if (this.$get(post, 'showComments')==true) {
       this.$set(post, 'showComments', false) ;
      return
    }

The code above thoes not work and I get this error:

Uncaught TypeError: this.$get is not a function

So I'm wondering how can I acheive this functionaliry.

解决方案

You should be able to simply read the dynamic property and reapply the value.

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>

这篇关于Vue.js 中 $set 的反义词是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆