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 id
the activeId
and props to determine if it is the currently active item. While this works, the problem is that every time activeId
the 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 active
prop instead:
<option
v-for="item in list"
:id="item.id"
:active="item.id === activeId" >
</option>
At this point, for most components, activeId
when changing, their active
props 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.