首页 > 解决方案 > 根据 vuejs 中的计算属性动态显示和隐藏按钮

问题描述

我想为特定用户发表的每条评论显示删除按钮,但我无法做到,我正在使用 v-bind 禁用其他评论的删除按钮,以便用户无法删除其他评论,但它仍然可见所有评论,即(也适用于其他用户)。假设我是一个用户,我评论了 3 次,然后删除按钮应该只显示在我的评论上,而不显示在其他评论上。有人可以帮我实现这一目标吗?

My code snippet is below

<div class="comment-list" v-for="comment in comments" :key="comment._id"> 
   <div class="paragraph" :class="[name, onCaretButtonClick ? 'paragraph' : 'hide']">
    <span class="names" id="comment-desc"> 
      <label class="comm-name">{{ comment.name }}</label>
      <button class="like-btn" id="like-comment"><i class="fas fa-heart"></i></button>
      <label> {{ comment.likes + ' likes' }} </label>
        <button v-bind:disabled="isCommentIdMatched" v-on:click="deleteComment(comment.userId)" 
         class="del-btn">delete</button>
    </span>
    <p>{{ comment.comment }}</p>
  </div>
</div>

下面是我正在使用的 deleteComment 函数和计算属性

computed: {
comments() {
  return store.state.comments 
},
getUserId() {
  return store.state.user._id
},
isCommentIdMatched() {
  let comments = store.state.comments
  let value = false
  if(comments) {
    comments.forEach((comment) => {
      if(comment.userId.match(this.getUserId)) {
        value = true
      }
    })
    return value
  }
  else {
    return value
  }
}

},

 methods: {
   deleteComment: function(commentUserId) {
   let userId = store.state.user._id
   if(commentUserId.match(userId)) {
    console.log('yes matched')
   }
 },

}

标签: vue.jsv-modelconditional-rendering

解决方案


无需编写 isCommentIdMatched 属性,而是可以使用更改一些行。

在下面的行中添加 v-bind="comments"

<div v-bind="comments" class="comment-list" v-for="comment in comments" :key="comment._id">

并在下面的按钮中添加 v-if="comment.userId && comment.userId.match(getUserId)"

<button v-if="comment.userId && comment.userId.match(getUserId)" v-on:click="deleteComment(comment.userId)" class="del-btn">delete</button>

推荐阅读