【问题标题】:Dynamically change icon variant in Vue在 Vue 中动态更改图标变体
【发布时间】:2021-08-23 16:55:39
【问题描述】:

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>

我想要完成的是当用户单击相应的vote-btn 时,根据upvoteVariantdownvoteVariantb-icon 变体更改为各自的值。以下是绑定到 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 的变体没有改变,即使数据发生了变化?

【问题讨论】:

    标签: javascript html vue.js bootstrap-4


    【解决方案1】:

    假设upvoteddownvoted 最初不在news 对象中(它们分别由upvote()downvote() 插入),Vue 2 cannot detect addition/deletion of properties in objects

    作为一种解决方法,您可以使用 this.$set():

    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) ?
        },
      }
    }
    

    demo

    【讨论】:

      猜你喜欢
      • 2019-01-29
      • 2023-03-21
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 2020-12-29
      • 1970-01-01
      • 2013-04-25
      相关资源
      最近更新 更多