简体   繁体   English

具有条件渲染的 Vue 组件功能

[英]Vue Component Functionality with Conditional Rendering

I have a vue component called <PlanView/> , and I'm rendering this component conditionally:我有一个名为<PlanView/>vue组件,我有条件地渲染这个组件:

<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以决定是否渲染模板

<PlanView :showPlan="show_plan"/>

Accept the prop inside PlanView component like接受PlanView组件内的道具,例如

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

Render the template of PlanView only if the prop is satisfied.仅在满足 prop 时渲染PlanView的模板。 So the template of PlanView will be looking like所以PlanView的模板看起来像

<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只需在包装器上使用v-show即可加载元素,但当条件为 false 时不会在 UI 中显示

<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.您可以简单地使用v-show而不是v-if来提供与@Nitheesh 建议的答案相同的功能。

<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 .但我不确定这就是你调用功能的意思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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