本文介绍了为什么我的 Vue 组件需要 :key?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个小的 Vue.js 组件,它显示一个最喜欢的星形图标.单击图标收藏/取消收藏该元素.到目前为止,我只实现了 UI 部分,如下所示:
<div :key="收藏夹"><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>
</模板><脚本>导出默认{数据() {返回 {最喜欢的:真的,}},安装(){},方法: {切换收藏夹(){this.favorite = !this.favorite}},道具:['team-id'],}<样式范围></风格>
如您所见,逻辑非常简单.
这很好用,但让我烦恼的一件事是,如果我从模板中删除 :key
属性,则单击它时图标不会更新(即使我已检查基础属性确实更新正确).添加 :key
使其工作,我想是因为它强制 Vue.js 在 favorite
更新时完全重新渲染组件.
为什么会这样?我对 JS 框架的世界还很陌生,所以请原谅我可能遗漏的任何明显的东西.我在网上做了一些研究,但找不到解释.我只是想确保我以正确的方式做事,而不仅仅是在这里解决问题.
解决方案
无论框架如何,它似乎都是 FontAwesome CSS 的普遍问题.github 上有一个问题,这里也有同样的问题 react https://github.com/FortAwesome/Font-Awesome/issues/11967
为了证明这一点,这里是同一示例的简化版本,但使用了引导程序图标
new Vue({el: '#app',数据() {返回 {最爱:真的}}});
I have a small Vue.js component which displays a favorite star icon. Clicking on the icon favorites/unfavorites the element. So far I have only implemented the UI part, which looks like this:
<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>
As you can see, the logic is pretty simple.
This works well, but one thing that bothers me is that, if I remove the :key
property from my template, the icon is not updated when I click on it (even though I have checked that the underlying property is indeed updated correctly). Adding :key
makes it work, I imagine because it forces Vue.js to completely re-render the component when favorite
is updated.
Why is this happening? I'm fairly new to the world of JS frameworks, so forgive any obvious stuff I might be missing. I did some research online but couldn't find an explanation. I just want to make sure I'm doing things the right way and not merely hacking around the issue here.
解决方案
Its seems to be a general issue of FontAwesome CSS regardless the framework.There is an issue on github and here the same issue with react https://github.com/FortAwesome/Font-Awesome/issues/11967
To prove that, here is a simplified version of the same example but using bootstrap icons
new Vue({
el: '#app',
data() {
return {
fav: true
}
}
});
<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>
这篇关于为什么我的 Vue 组件需要 :key?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!