v-else is getting rendered first instead v-if in Vue JS

1.5k Views Asked by At

I have an HTML element like below

<div v-if="showOriginalContent"> original content</div>
<div v-else> default content </div>

initial value of showOriginalContent is false and from mounted method am calling an another method where i will make the value of showOriginalContent to true based on some conditions . Currently even if the showOriginalContent is true i can see that v-else is getting displayed for a fraction of seconds before v-if is rendered in the DOM . How can i solve this issue ? I tried to move the function call to all other life cycle methods but nothing is working . I have gone through before and after navigation approach in vue js ,Is it possible to apply that logic here?

4

There are 4 best solutions below

1
On

I think it's normal if I understood correctly what you posed as the problem.

Because the mounted state is called when the view has already been OK and displayed and only once.

So a variable declaring in this method its change will not necessarily have an effect on what should be displayed.

Try to see the lifecycle in Vuejs for more detail.

Put it in computed or watch methods to see.

1
On

Use an outer div and control this div with another variable that will be true when you are done with your condition parts in mounted hook.. like this..

<div v-if="conditioncheckdone">
<div v-if="showOriginalContent"> original content</div>
<div v-else> default content </div>
</div>

It will resolve your issue of displaying v-else stuff while you are checking your conditions in mounted

0
On

You can ensure your original content is hidden by setting the value of showOriginalContent to something that is not false... say an empty string '' and show your content only if showOriginalContent is the boolean you expect like so. This way, the content will not show unless it is changed to either true or false on mounting. Someone correct me if it is against any best practices. Cheers.

<div v-if="showOriginalContent===true"> original content</div>
<div v-if="showOriginalContent===false"> default content </div>
0
On

turn the default showOriginalContent value to null instead of false