简体   繁体   中英

Vue Component Functionality with Conditional Rendering

I have a vue component called <PlanView/> , and I'm rendering this component conditionally:

<div v-if="show_plan" id="mainplan">
  <PlanView/>
</div>
<div class="icon" v-else>
  <font-awesome-icon icon="fa-solid fa-angles-right" @click="openPlan"/>
</div>
openPlan() {
    this.show_plan = true;
},

but I want the functionality to be called even if the component is not rendered, can you please advise me how can I do that? thanks in advance.

If you want the component to be renedered and not displayed, you can hide the visibility of the template inside the component rather than hiding the complete compoenent.

Pass a prop to PlanView to decide the template is to be rendered or not

<PlanView :showPlan="show_plan"/>

Accept the prop inside PlanView component like

defineProps({
    showPlan: {
        type: Boolean,
        required: false,
        default: false
    }
})

Render the template of PlanView only if the prop is satisfied. So the template of PlanView will be looking like

<template>
    <!-- Div or some wraper element -->
    <div v-if="showPlan"> 
        <!-- Rest of your template here -->
    </div>
</template>

OR

Simply use v-show on the wrapper so that the element will be loaded, but will not be displayed in the UI when the condition is false

<PlanView v-show="show_plan"/>

You can simply use v-show instead of v-if to provide the same functionality as the answer from @Nitheesh suggests.

<div v-show="show_plan" id="mainplan">
  <PlanView/>
</div>
<div v-show="!show_plan" class="icon">
  <font-awesome-icon icon="fa-solid fa-angles-right" @click="openPlan"/>
</div>

But I am not sure this is what you means by by calling the functionality .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM