why component is not destroyed under v-if
This is the intended functionality for Vue. In order to let Vue know that the component shouldn't be reused but instead destroyed and create a different component, add a key
attribute to the components.
Example:
<div v-if="show1">
<my-comp title="comp1" key="somekeyhere"/>
</div>
<div v-else>
<my-comp title="comp2" key="someotherkeyhere"/>
</div>
Note that you could also put the key
attribute to the div
, but I think it's cleaner to add it on the component since the div
itself can be reused without issues.
Here's a little trick (or horrible hack if you like) if you want your component to always be destroyed when it is hidden (e.g. to save memory). Use NaN
as the key
. Since NaN
is never equal to itself Vue will always think it is a different element.
<div v-if="show1">
<my-comp title="comp1" :key="NaN"/>
</div>
<div v-if="!show1">
<my-comp title="comp2" :key="NaN"/>
</div>
You need :key=
rather than key=
because otherwise the attribute will be a string with the value "NaN"
.