Home > database >  Adding conditional Components to template Vuejs
Adding conditional Components to template Vuejs

Time:04-12

I have a list of different events such as below which is being imported as logTypes

export default {
  LOGIN: "login",
  LOGOUT: "logout",
}

And I have 2 different components for both of these events.

<LogTypeLogin :item="item" />
<LogTypeLogout :item="item" />

in my template, I have this

<template #item.event="{ item }">
  <div v-else-if="item.action === logTypes.LOGIN">
     <LogTypeLogin :item="item" />
  </div>
  <div v-else-if="item.action === logTypes.LOGOUT">
     <LogTypeLogout :item="item" />
  </div>
  <div v-else>
    Nothing
  </div>
</template>

Everything is working fine but I want to make it more readable such

in <template #item.event="{ item }">

I want to loop through logTypes and select Component on the basis of that instead of if and else?

any help will be wonderful. thank you.

CodePudding user response:

Try to name the components with LOGIN and LOGOUT as in logTypes object:


components:{
   LOGIN:LogTypeLogin ,
   LOGOUT:LogTypeLogout
}

then use the buitl-in component component and bind the is prop to item.action :


<template #item.event="{ item }">
  <component v-if="item.action" :is="item.action" :item="item" />
  <div v-else>
    Nothing
  </div>
</template>

  • Related