Reputation: 24061
I have a button component that loads comments. The comments are a separate component.
How can on click of the button can I load a child component? Is it a simple case of using v-if on the child component? Or is there a more efficient way?
e.g.
<template>
<div class="comment-btn" @click="toggleActive">
<img src="/img/comment-btn.svg">
</div>
<comments v-if="active"></comments>
</template>
EDIT:
I've been reading about mount, would that be better?
Upvotes: 2
Views: 1423
Reputation: 7220
v-if
and v-show
are both perfectly acceptable options. The questions you'll need to ask yourself, however, are "do I need the child component to do anything on being toggled?" and "do I need any data in the child component to be persisted?". Based on your exact program needs, you'll want to choose accordingly.
Here is a general description of the solutions you'll need based on your answers:
1) If you don't need anything to happen on toggling but you need data persisted, use v-show
.
2) If you don't need anything to happen on toggling and you want data to be cleared out, use v-if
.
3) If you need something to happen on toggling and you want data persisted, use v-if
and the mounted
lifecycle hook for triggering the event, and $emit
any data to your parent component so it can be restored later. Alternatively, use v-show
and a watch
a particular props
value.
4) If you need something to happen on toggling and don't need your data persisted, then just use v-if
and the mounted
lifecycle hook for triggering the event.
Upvotes: 5