Dhiraj Wakchaure
Dhiraj Wakchaure

Reputation: 2706

vuejs mounted is called even if component was not loaded via v-if

I am using vuejs for my app look like this

app.vue

<template>
<div>
 <custom-elem v-if="somefalseCondition"> </custom-elem>
</div>
</template>

CustomElem.vue

<template>
  some code
 </template>
<script> 
export default {
 mounted(){
  console.log('demo')
}
}
</script>

I am expecting this mounted should be called when element is actually rendered on screen , but it is executing even after condition inside v-if is false , what am i missing here ?

Upvotes: 10

Views: 13575

Answers (4)

Umair Abid
Umair Abid

Reputation: 1463

Well according to documentation here , It reads

Called after the instance has been mounted, where el is replaced by the newly created vm.$el. If the root instance is mounted to an in-document element, vm.$el will also be in-document when mounted is called.

Note that where it says where instance is mounted and not when template is rendered, which basically means as your component is called the component class will be loaded and mounted hook will be called. It makes sense because when your v-if becomes true, merely its template will be added and actual component class will not be loaded

Upvotes: 1

Irakli Kandelaki
Irakli Kandelaki

Reputation: 106

I can confirm this, even if you outsource it to a portal. Everything you do in the mounted hook of the component, is actually "doing his job." You simply don't see it until the template is rendered. One way to fix this is to place the function you run in the mounted hook inside the if() condition itself.

For example, I had the function that called e.preventDefault on the mousemove event, even though the component was in v-if and wasn't rendered, it still messed up my input range slider, I couldn't drag it as expected.

Upvotes: 1

Slim
Slim

Reputation: 1276

That is not correct, there must be a mistake somewhere.

v-if="false" avoid the creation of the component instance.

No event (beforeCreate, created, mounted...) is triggered if v-if is allways falsy.

Are you sure that your condition is allways falsy? This must be the case since the beginning of your parent component, be careful about changing values, if any data passing inside your condition is not falsey at some point of time, component will be instanciated and events raised.

Regards

Upvotes: 5

holla
holla

Reputation: 161

I think instead of using mounted() the lifecycle hook you are looking for is created(). if you use console.log() in created(), it'll not be called.

Upvotes: 2

Related Questions