In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
这篇文章主要介绍"怎么使用Key对Vue组件进行重新渲染",在日常操作中,相信很多人在怎么使用Key对Vue组件进行重新渲染问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"怎么使用Key对Vue组件进行重新渲染"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
通过改变 key 的值来重新渲染组件
我最喜欢的方法是使用key属性,因为使用key 的方式,Vue 就知道了特定组件与特定数据相关。
如果 key保持不变,则不会更改组件。但是,如果key发生更改, Vue 知道它应该删除旧组件并创建一个新组件。
下面是一个非常基本的方法:
export default { data() { return { componentKey: 0, }; }, methods: { forceRerender() { this.componentKey += 1; } } }
每次调用forceRerender时,componentKey 的值就会更改。当componentKey 的值发生改变时,Vue 就知道把ComponentToReRender组件删除并创建一个新组件。
这样ComponentToReRender就会重新渲染并重置里面的状态。nice nice!
强制多个子节点进行更新
同样用这种方式也可以用于多个子组件:
export default { data() { return { key1: 0, key2: 0, }; }, methods: { forceRerender(child) { if (child === 1) { this.key1 += 1; } else if( child === 2) { this.key2 += 1; } } } }
这里我们使用了两个单独 key 来分别控制每个子组件是否重新渲染。将它们分开是为了其中的一个子组件渲染,不会影响到另外另一个。
但如果希望两个子组件总是一起更新,则可以使用相同的 kye。但是,key必须是唯一的,所以下面这种方式,不能工作:
export default { data() { return { componentKey: 0, }; }, methods: { forceRerender(child) { this.componentKey += 1; } } }
在这里,仅第一个Child组件会被渲染。第二个被忽略,因为它具有重复的key 了。
为了解决这个问题,我们可以基于componentKey为每个孩子构造一个新key:
export default { data() { return { componentKey: 0, }; }, methods: { forceRerender(child) { this.componentKey += 1; } } }
因为我们每次在componentKey后面添加-1和-2,所以这两个key始终是唯一的,现在这两个组件都将被重新渲染。
如果是在列表中,则可以使用如下方式:
export default { data() { return { list: [ // ... ], componentKey: 0, }; }, methods: { forceRerender(child) { this.componentKey += 1; } } }
在这里,我们将key构造为${componentKey}-${index},因此列表中的每个项目都会获得唯一的key,只要componentKey一改变,列表中的所有组件将同时重新渲染。
当然,还有更简单的方式,就是用div把列表包裹起来,直接对 div重新更新就行了:
export default { data() { return { list: [ // ... ], componentKey: 0, }; }, methods: { forceRerender(child) { this.componentKey += 1; } } } 到此,关于"怎么使用Key对Vue组件进行重新渲染"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.