在 Vue 中动态更改图标变体

时间:2021-06-06 09:15:02

标签: javascript html vue.js bootstrap-4

我有以下模板,当 data 中的值发生更改时,我尝试动态更改该模板:

<div class="vote-bar-content">
  <button class="vote-btn" @click="upvote(news)">
    <b-icon icon="chevron-up" 
    :variant="upvoteVariant(news)"></b-icon>
  </button>
  <span class="vote"> No. of vote goes here </span>
  <button class="vote-btn" @click="downvote(news)" >
    <b-icon icon="chevron-down"
    :variant="downvoteVariant(news)"></b-icon>
  </button>
</div>

我想要完成的是当用户点击相应的 b-icon 时,根据 upvoteVariantdownvoteVariantvote-btn 变体更改为各自的值.以下是绑定到 Vue 方法中列出的 b-icon 元素的两个函数:

upvoteVariant(news) {
  if (this.votingList[news._id].upvoted) {
    return 'warning'
  }
  else {
    return ''
  }
},

downvoteVariant(news) {
  if (this.votingList[news._id].downvoted) {
    return 'primary'
  }
  else {
    return ''
  }
}

当按钮被点击并调用 upvote(news) 方法时,this.votingList[news._id] 会发生变化,并且值会改变,如下所示:

async upvote(news) {
  axios.post(serverSide.findUserByID, {userID: this.user._id})
  .then((res) => {
    this.user.rep = res.data.user.rep
    if (this.votingList[news._id].upvoted == true) {
      alert('You have already voted!')
      return
    }
    else {
      axios.post(serverSide.castVote, {
        // function params
      })
      .then(() => {
        this.votingList[news._id].upvoted = true
        alert("Vote Casted")
        console.log("Voting List: ", this.votingList[news._id])
        this.upvoteVariant(news)
        return
      })
    }
  })
},

那么为什么 b-icon 的变体在数据发生变化的情况下没有变化?

1 个答案:

答案 0 :(得分:0)

假设 upvoteddownvoted 最初不在 news 对象中(它们分别由 upvote()downvote() 插入),Vue 2 {{ 3}}。

作为一种解决方法,您可以使用 cannot detect addition/deletion of properties in objects

export default {
  methods: {
    async upvote(news) {
      const item = this.votingList[news._id]
      if (item.upvoted || item.downvoted) {
        alert('You have already voted!')
        return
      }
      this.$set(item, 'upvoted', true) ?
    },
  }
}

this.$set()

相关问题