Search code examples
javascriptvue.jsvue-component

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.


Solution

  • 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"/>