As shown in the figure, when four buttons are clicked in sequence to display four different icons, why is the created method of the icon component only called the first time
三叔2017-06-12 09:25:16
This phenomenon is very interesting. I have never noticed it. The specific reason is still under study.
It is speculated from the phenomenon that it may be caused by the introduction of virtual DOM in the vue2.x version, which brings about some optimization processes (because the 1.x version does not have this phenomenon).
It seems that in the process of dynamically creating icon instances, the framework makes a judgment and uses the least instance for rendering. For example, when the index value changes, from 1 to 2, Vue knows that there is currently an icon instance, and only one icon instance will be displayed in the future, so the existing instance is reused. The same goes for the whole process, so it is only once create occurs. If the above four v-if conditions are modified to have two conditions met at a certain moment (that is, two icons are displayed at the same time), then create will occur twice.
Update:
Evidence was found on the official website. Regarding the use of keys, it is usually in list rendering:
The key special attribute is primarily used as a hint for Vue's virtual DOM algorithm to identify VNodes when diffing the new list of nodes against the old list. Without keys, Vue uses an algorithm that minimizes element movement and tries to patch/reuse elements of the same type in-place as much as possible. With keys, it will reorder elements based on the order change of keys, and elements with keys that are no longer present will always be removed/destroyed.
But the official website also says:
It can also be used to force replacement of an element/component instead of reusing it. This can be useful when you want to: Properly trigger lifecycle hooks of a component
It is indeed the optimization process of virtual DOM. If you want the above icon to be created every time, add a different key attribute to each one.
三叔2017-06-12 09:25:16
I don’t quite understand what question you are asking. You can take a look at vue’s vue life cycle hook