AutoComplete Component with Vue Composition API in VueJS

Aaron K Saunders - Apr 11 '20 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .