Creating a custom select tag is with your own styling is notoriously difficult. Sometimes it’s impossible without building your own from scratch using a combination of styled **divs **and custom JavaScript. In this article, you’ll learn how to build a Vue custom select component that can be easily be styled using your own CSS. In fact, it’s the same component that we use in production on Qvault, and you can see it in action on the playground.

Vue Custom Select Example

Code Sandbox Demo

The HTML

<template>
  <div class="custom-select" :tabindex="tabindex" @blur="open = false">
    <div class="selected" :class="{ open: open }" @click="open = !open">
      {{ selected }}
    </div>
    <div class="items" :class="{ selectHide: !open }">
      <div
        v-for="(option, i) of options"
        :key="i"
        @click="
          selected = option;
          open = false;
          $emit('input', option);
        "
      >
        {{ option }}
      </div>
    </div>
  </div>
</template>

The following is important to note:

  • The tabindex property allows our component to be focused, which in turn allows it to be blurred. The blur event closes our component when a user clicks outside of the component.
  • By emitting the selected option using the ‘input’ parameter, the parent component can react to changes.

#javascript #languages #vue #frontend #javascript #vue #vue.js

How to Make a Simple Vue Custom Select Component
33.10 GEEK