For 2 same components with v-if and v-else, mounted hook is only called once

HTML code:

<div id="example">
  <my-component text="first" v-if="test"></my-component>
  <!-- expected mounted be called again, but not -->  
  <my-component text="second" v-else></my-component>
</div>

js code:

Vue.component('my-component', {
  template: '<div>{{text}}</div>',
  mounted: function () {
  	console.log('mounted')
  },
  props: ['text']
})

new Vue({
  el: '#example',
  data: function () {
  	return {
    	test: true
    }
  },
  mounted: function () {
    setTimeout(() => {
    	this.test = false;
    }, 1000)
  }
})

I expected after the test is set to false, my-component mounted method will be called again, so I can do some initialization. But it doesn’t work as that.

Is it designed as that? or a bug? Could someone give the related implementation(the related code)?

Set a unique key attribute so Vue knows that it should not reuse the component instance.

1 Like

Set a unique key attribute

Do you mean set key like following?

<div id="example">
  <my-component id='com1' text="first" v-if="test"></my-component>
  <!-- expected mounted be called again, but not -->  
  <my-component id='com2' text="second" v-else></my-component>
</div>

I added different id, but it doesn’t work.

No, i mean literally “key”, as explained here in the documentation

<div id="example">
  <my-component key="something" text="first" v-if="test"></my-component>
  <!-- expected mounted be called again, but not -->  
  <my-component key="someotherthing" text="second" v-else></my-component>
</div>
3 Likes

Cool, it works.

@LinusBorg

Then how come this example is working without key

https://jsfiddle.net/Le5zw6av/24/

Because you render all three components without any v-if.

The key is required of you switch one component instance for another in the same place, in order to tell Vue to not re-use the same instance, but create a fresh one.

It’s all explained in the linked documentation.

1 Like

Found this thread when working on the same problem, best solution !
Thank you