【问题标题】:dynamically show and hide button according to computed property in vuejs根据 vuejs 中的计算属性动态显示和隐藏按钮
【发布时间】:2020-11-23 12:38:12
【问题描述】:

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

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.js v-model conditional-rendering


    【解决方案1】:

    不需要写 isCommentIdMatched 属性,你可以改一些行。

    在下面一行添加 v-bind="cmets"

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

    【讨论】:

      猜你喜欢
      • 2018-03-29
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 2016-12-24
      • 2020-04-09
      • 2021-03-09
      • 1970-01-01
      相关资源
      最近更新 更多