DEV Community

Cover image for AutoComplete Component with Vue Composition API in VueJS
Aaron K Saunders
Aaron K Saunders

Posted on

2 2

AutoComplete Component with Vue Composition API in VueJS

Simple AutoComplete Component built using a custom built useAutoComplete hook I built using the vue composition api. Since I am quite fond of Ionic Framework's Web Components, I used the components to construct a clean presentation of the work.

The hook takes in two parameters, options which is the array of data to search, and optionKey which is what property in the array of objects to search on.

I this example I have loaded in some data from RandomUser.me to populate the array of data and I am used the email property as my filter.

The dropdown that appears in the ion-card component from Ionic Framework; and the rest of the magic is accomplished using css with some position.

import { toRefs, reactive } from "@vue/composition-api";

/**
 *
 */
const useAutoComplete = (options, key) => {
  let state = reactive({
    userInput: "",
    filteredSuggestions: [],
    suggestions: options,
    selectedItem: {}
  });

  let selected = _item => {
    state.userInput = _item[key];
    state.filteredSuggestions = [];
    state.selectedItem = { userInput: state.userInput, item: _item };
  };

  let onChange = _event => {
    let i = state.userInput;
    state.selectedItem = { userInput: state.userInput, item: null };
    if (i.length === 0) {
      state.filteredSuggestions = [];
      return;
    }
    const r = state.suggestions.filter(
      suggestion => suggestion[key].toLowerCase().indexOf(i.toLowerCase()) > -1
    );
    console.log(r);
    state.filteredSuggestions = r;
  };
  return {
    ...toRefs(state),
    selected,
    onChange
  };
};

export default useAutoComplete;

Enter fullscreen mode Exit fullscreen mode

Full Source Code

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay