Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Vue do not use both v-if and v-for instructions on the same element

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you vue do not use v-if and v-for instructions on the same element at the same time, I hope you will learn something after reading this article, let's discuss it together!

Do not use both v-if and v-for instructions on the same element

To filter elements in an array, it is easy to use v-if and v-for on the same element at the same time.

/ / A bad practice

The problem is that the v-for instruction takes precedence over the v-if instruction in Vue. It loops through each element and then checks the v-if condition.

This.products.map (function (product) {if (product.price)

< 500) { return product }}) 这意味着,即使我们只想渲染列表中的几个元素,也必须遍历整个数组。 这对我们来当然没有任何好处。 一个更聪明的解决方案是遍历一个计算属性,可以把上面的例子重构成下面这样的: computed: { cheapProducts: () =>

{return this.products.filter (function (product) {return product.price < 100})}}

This has several benefits:

Rendering is more efficient because we don't traverse all the elements

The filtered list is reused only when the dependency changes

This writing helps to separate the component logic from the template, making the component more readable.

After reading this article, I believe you have a certain understanding of "vue do not use v-if and v-for instructions on the same element at the same time". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report