Thinking -- vue performance optimization: keep props stable

The Thinking series aims to convey a programming idea that can be implemented in 10 minutes.

In Vue, changes to component props cause the component to update. Therefore, ensuring that component props remain stable can effectively reduce the number of updates and improve efficiency.

Example:

<option
  v-for="item in list"
  :id="item.id"
  :active-id="activeId" >
</option>  

In <option>the component , it uses idthe activeIdand props to determine if it is the currently active item. While this works, the problem is that every time activeIdthe is updated , every <option> in the list is updated!

Ideally, only items whose active state has changed should be updated. We can do this by moving the active state comparison logic into the parent component, and <option>let accept a activeprop instead:

<option
  v-for="item in list"
  :id="item.id"
  :active="item.id === activeId" >
</option>  

At this point, for most components, activeIdwhen changing, their activeprops will remain the same, so they don't need to be updated.

To sum up, the core idea of ​​this technique is to keep the props passed to subcomponents as stable as possible.

Guess you like

Origin blog.csdn.net/ligang2585116/article/details/129856814