skip to Main Content

I’m trying to display icon when condition is passed and for that I’m using theme icon

Script Code
<script setup>
import { h } from 'vue'
const props = defineProps({
  itemDetail: Object
});

const passedIcon = h('i', {class: 'bx bxs-check-circle'});
const failedIcon = h('i', {class: 'bx bxs-cross-circle'});
</script>
Template Code
<template>
 <tr>
  <td>Zip check</td>
  <td>
   {{ props.itemDetail.status == 'pass' ? 'Passed ' + passedIcon : 'Failed ' + failedIcon }}
  </td>
 </tr>
</template>

But It’s returning

Passed [object Object]

or 

Failed [object Object]

I had tried with h() render function but passed directly through .innerHTML which works fine but How can I achieve to directly call as html with h() render function in the template?

2

Answers


  1. Vue SFC Playground

    Convert your functional components to functions – they are called functional for a reason:

    <script setup>
    import { h } from 'vue'
    const props = defineProps({
      itemDetail: {type: Object, default: {}}
    });
    
    const passedIcon = () => h('i', {class: 'bx bxs-check-circle'});
    const failedIcon = () => h('i', {class: 'bx bxs-cross-circle'});
    </script>
    
    <template>
     <tr>
      <td>Zip check</td>
      <td>
      <template v-if="itemDetail.status == 'pass'">Passed <passed-icon /></template>
       <template v-else>Failed <failed-icon /></template>
      </td>
     </tr>
    </template>
    
    Login or Signup to reply.
  2. You could use the built-in component component with its prop is bound to the icon based on the condition :

    <script setup>
    import { h, computed } from 'vue'
    const props = defineProps({
      itemDetail: Object
    });
    
    const passedIcon = h('i', { class: 'bx bxs-check-circle' }, );
    const failedIcon = h('i', { class: 'bx bxs-cross-circle' }, );
    const icon = computed(() => {
      return props.itemDetail.status == 'pass' ? passedIcon : failedIcon
    })
    </script>
    
    <template>
      <tr>
        <td>Zip check</td>
        <td>
          {{ itemDetail.status == 'pass' ? 'Passed ' : 'Failed ' }}
          <component :is="icon" />
        </td>
      </tr>
    </template>
    
    

    DEMO

    You could also avoid repeating the conditional statement by refactoring the vnode created by h:

    const passedContent = h('span',{},['Passed',h('i', {class: 'bx bxs-check-circle'})]);
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search