Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why component is not destroyed under v-if

Tags:

vue.js

I have very simple example. There are two divs each with v-if with same variable, one with true and one with false. There is component nested inside the each of the divs (same component).

What I see (from the console.log) is that even there is v-if, the component is not destroyed and created but rather reused.

Is this bug? feature? Because I was relying on them to be destroyed (the problem occur in some more complex component).

Thanks.

Html and javascript below, there is also jsfiddle https://jsfiddle.net/ekeydar/p64ewLd1/3/

This is the html:

<div id="app">
  <button @click="show1=!show1">
    Toggle  
  </button>
  <div v-if="show1">
    <my-comp title="comp1"/>
  </div>
  <div v-if="!show1">
    <my-comp title="comp2"/>
  </div>
</div>

This is the javascript:

Vue.component('my-comp', {
    props: ['title'],
  template: '<h1>{{title}}</h1>',
  created: function() {
    console.log('my-comp.created title='+ this.title);
  },
  destroyed: function()  {
    console.log('my-comp.destroyed title='+ this.title);
  }
}),

new Vue({
  el: '#app',
  data: {
    show1: true,
  },
})
like image 430
eran Avatar asked Oct 31 '18 14:10

eran


People also ask

Does V-if destroy component?

v-if is "real" conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created during toggles.

What is the difference between V-if and V show?

The key difference is that v-if conditionally renders elements and v-show conditionally displayselements. This means that v-if will actually destroy and recreate elements when the conditional is toggled. Meanwhile, v-show will always keep the element in the DOM and will only toggle its display by changing its CSS.

What is V-if in VUE JS?

The v-if directive is a Vue. js directive used to toggle the display CSS property of a element with a condition. If the condition is true it will make it visible else it will make it invisible.

How do you hide an element in Vue?

Vue gives you a bunch of good ways to hide the element on the screen. When using v-if="false" the element isn't rendered at all in the DOM. When using v-show="false" the element is rendered in the DOM, however, Vue applies the inline style display: none that hides the element completely.


1 Answers

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".

like image 58
Timmmm Avatar answered Sep 21 '22 15:09

Timmmm