Add image to select options

Learn how to create a custom option slot with images.

To add image to select, we can use option and single-label slots:

template
<template>
  <Vueform>
    <SelectElement name="select" :native="false" :items="[
      { value: 'judy', name: 'Judy', image: '/images/random-user-3.jpg' },
      { value: 'jane', name: 'Jane', image: '/images/random-user-4.jpg' },
      { value: 'john', name: 'John', image: '/images/random-user-1.jpg' },
      { value: 'joe', name: 'Joe', image: '/images/random-user-2.jpg' }
    ]">
      <!-- Option -->
      <template v-slot:option="{ option }">
        <img class="rounded-full w-6 h-6 mr-1.5" :src="option.image">
        {{ option.name }}
      </template>
      <!-- Selected option -->
      <template v-slot:single-label="{ value }">
        <div class="flex items-center h-full absolute left-0 top-0 pointer-events-none bg-transparent leading-snug pl-3">
          <img class="rounded-full w-6 h-6 mr-1.5" :src="value.image"> {{ value.name }}
        </div>
      </template>
    </SelectElement>
  </Vueform>
</template>
vue
<template>
  <Vueform :schema />
</template>

<script setup>
import { ref } from 'vue'

const SelectOptionImageSlot = {
  props: ['option'],
  render() {
    return h('div', { class: 'flex' }, [
      h('img', {
        class: 'rounded-full w-6 h-6 mr-1.5',
        src: this.option.image,
      }),
      this.option.name
    ])
  }
}

const SelectSingleLabelImageSlot = {
  props: ['value'],
  render() {
    return h('div', { class: 'flex items-center h-full absolute left-0 top-0 pointer-events-none bg-transparent leading-snug pl-3' }, [
      h('img', {
        class: 'rounded-full w-6 h-6 mr-1.5',
        src: this.value.image,
      }),
      this.value.name
    ])
  }
}

const schema = ref({
  select: {
    type: 'select',
    native: false,
    items: [
      { value: 'judy', name: 'Judy', image: '/images/random-user-3.jpg' },
      { value: 'jane', name: 'Jane', image: '/images/random-user-4.jpg' },
      { value: 'john', name: 'John', image: '/images/random-user-1.jpg' },
      { value: 'joe', name: 'Joe', image: '/images/random-user-2.jpg' }
    ],
    slots: {
      // Option
      option: SelectOptionImageSlot,
      // Selected option
      singleLabel: SelectSingleLabelImageSlot,
    }
  }
})
</script>
  
👋 Hire Vueform team for form customizations and developmentLearn more