hey I am building an spa app with vuejs 3 and I am stuck with v-if and v-else not working as intended
<div v-if="this.isScroll" @click = "toggleIsScroll" class ="spinner-container ">
<i ref = "icon" class = "bi bi-pause-fill icon"> </i>
<div ref="spinner" class ="spinner-border text-dark loader "> </div>
</div>
<div v-else @click = "toggleIsScroll" class ="spinner-container ">
<i ref = "icon" class = "bi bi-play-fill icon"> </i>
<div ref="spinner" class ="spinner-border text-dark loader visually-hidden"> </div>
</div>
the docs says that v-else needs to come right after v-if but I don't know if it works if v-if has children inside it i have tried to create the v-if section and v-else section in separate components and use v-if and v-else on those as follows
<CustomComponent v-if="this.IsScroll"/>
<SecondCustomComponent v-else/>
but it just renders both components always so how should I go about this? can you use v-else on followed v-if element even if the v-if one has child elements before the v-else?
CodePudding user response:
When it comes to displaying components conditionally, it would be best to go with v-show
since it won't re-render every time when you make it hide/show
<CustomComponent v-show="this.IsScroll"/>
<SecondCustomComponent v-show="!this.IsScroll"/>
CodePudding user response:
v-if and v-else should work with children inside the element. Also you don't need to do v-if="this.isScroll" but just v-if="isScroll".
CodePudding user response:
Assuming that IsScroll is set in the data, the this
is not required.
Use v-show
if you need to toggle something often, and use v-if
if the condition is unlikely to change at runtime.
data: {
IsScroll: true
},
methods:{
toggleIsScroll(){
.....
}
}
<div v-if="isScroll" @click= "toggleIsScroll" class ="spinner-container ">
<i ref = "icon" class = "bi bi-pause-fill icon"> </i>
<div ref="spinner" class ="spinner-border text-dark loader "> </div>
</div>
<div v-else @click= "toggleIsScroll" class ="spinner-container ">
<i ref = "icon" class = "bi bi-play-fill icon"> </i>
<div ref="spinner" class ="spinner-border text-dark loader visually-hidden"> </div>
</div>