为什么我的Vue组件需要:key?

Ale*_*tis 6 vue.js vuejs2

我有一个小的Vue.js组件,它显示了一个喜欢的星形图标.点击图标收藏夹/不喜欢该元素.到目前为止,我只实现了UI部分,如下所示:

<template>
  <div :key="favorite">
    <a v-on:click="toggleFavorite" style="cursor: pointer">
      <i v-show="favorite" class="text-warning fas fa-star"></i>
      <i v-show="!favorite" class="text-warning far fa-star"></i>
    </a>
  </div>
</template>

<script>
export default {
  data() {
    return {
      favorite: true,
    }
  },
  mounted() {
  },
  methods: {
    toggleFavorite() {
      this.favorite = !this.favorite
    }
  },
  props: ['team-id'],
}
</script>

<style scoped>
</style>
Run Code Online (Sandbox Code Playgroud)

如您所见,逻辑非常简单.

这种运作良好,但有一件事困扰我的是,如果我删除了:key从我的模板特性,图标是不是当我点击它更新(即使我已经检查了相关物业确实正确更新).添加:key使它工作,我想是因为它强制Vue.js在favorite更新时完全重新渲染组件.

为什么会这样?我对JS框架的世界相当新,所以请原谅我可能遗漏的任何明显的东西.我在网上做了一些研究,但找不到解释.我只是想确保我以正确的方式做事,而不仅仅是在这里解决这个问题.

Dob*_*leL 2

无论框架如何,这似乎都是 FontAwesome CSS 的普遍问题。github上有一个问题,这里的react也有同样的问题https://github.com/FortAwesome/Font-Awesome/issues/11967

为了证明这一点,这是同一示例的简化版本,但使用引导图标

new Vue({
  el: '#app',
  data() {
    return { 
      fav: true
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
<script
  src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"
></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

<div id="app">
  <div>
    <a v-on:click="fav = !fav" style="cursor: pointer">
      <i v-show="fav" class="glyphicon glyphicon-star"></i>
      <i v-show="!fav" class="glyphicon glyphicon-star-empty"></i>
    </a>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)