GithubHelp home page GithubHelp logo

dominikklein / vue-autosuggest Goto Github PK

View Code? Open in Web Editor NEW

This project forked from darrenjennings/vue-autosuggest

0.0 1.0 0.0 2.02 MB

๐Ÿ” Vue autosuggest component.

Home Page: https://educents.github.io/vue-autosuggest/storybook

License: MIT License

JavaScript 62.29% HTML 4.64% Vue 33.07%

vue-autosuggest's Introduction

vue-autosuggest

๐Ÿ” Autosuggest component built for Vue.


Build Status Code Coverage version downloads MIT License

All Contributors PRs Welcome Code of Conduct

Watch on GitHub Star on GitHub Tweet

Table of Contents

Examples

Features

  • WAI-ARIA complete autosuggest component built with the power of Vue.
  • Full control over rendering with built in defaults or custom components for rendering.
  • Easily integrate AJAX data fetching for list presentation.
  • Supports multiple sections.
  • No opinions on CSS, full control over styling.
  • Rigorously tested.

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm install --save vue-autosuggest

or

yarn add vue-autosuggest

Usage

Load VueAutosuggest into your vue app globally.

import VueAutosuggest from "vue-autosuggest";
Vue.use(VueAutosuggest);

or locally inside a component:

import { VueAutosuggest } from 'vue-autosuggest';
export default {
  ...
  components: {
      VueAutosuggest
  }
  ...
};

Place the component into your app!

<vue-autosuggest
    :suggestions="[{data:['Frodo', 'Samwise', 'Gandalf', 'Galadriel', 'Faramir', 'ร‰owyn']}]"
    @click="clickHandler"
    :on-selected="selectHandler"
    :input-props="{id:'autosuggest__input', onInputChange: this.onInputChange, placeholder:'Do you feel lucky, punk?'}"
/>

Advanced usage:

Click to expand

<template>
<div>
    <h1>Vue-autosuggest ๐Ÿ”ฎ</h1>
    <div style="padding-top:10px; margin-bottom: 10px;"><span v-if="selected">You have selected '{{JSON.stringify(selected,null,2)}}'</span></div>
        <vue-autosuggest
            :suggestions="filteredOptions"
            @focus="focusMe"
            @click="clickHandler"
            :on-selected="onSelected"
            :render-suggestion="renderSuggestion"
            :get-suggestion-value="getSuggestionValue"
            :input-props="{id:'autosuggest__input', onInputChange: this.onInputChange, placeholder:'Do you feel lucky, punk?'}"/>
</div>
</template>

<script>
import { VueAutosuggest } from "vue-autosuggest";

export default {
  components: {
    VueAutosuggest
  },
  data() {
    return {
      selected: "",
      filteredOptions: [],
      suggestions: [
        {
          data: [
            { id: 1, name: "Frodo", avatar: "./frodo.jpg" },
            { id: 2, name: "Samwise", avatar: "./samwise.jpg" },
            { id: 3, name: "Gandalf", avatar: "./gandalf.png" },
            { id: 4, name: "Aragorn", avatar: "./aragorn.jpg" }
          ]
        }
      ]
    };
  },
  methods: {
    onInputChange(text, oldText) {
      if (text === null) {
        /* Maybe the text is null but you wanna do
        * something else, but don't filter by null.
        */
        return;
      }

      // Full customizability over filtering
      const filteredData = this.suggestions[0].data.filter(option => {
        return option.name.toLowerCase().indexOf(text.toLowerCase()) > -1;
      });

      // Store data in one property, and filtered in another
      this.filteredOptions = [{ data: filteredData }];
    },
    clickHandler(item){
      // items are selected by default on click, but you can add some more behavior here!
    },
    onSelected(item) {
      this.selected = item;
    },
    renderSuggestion(suggestion) {
      /* You will need babel-plugin-transform-vue-jsx for this kind of full customizable
       * rendering. If you don't use babel or the jsx transform, then you can use this
       * function to just `return suggestion['propertyName'];`
       */
      const character = suggestion.item;
      return (
        <div
          style={{
            display: "flex",
            alignItems: "center"
          }}
        >
          <img
            style={{
              width: "25px",
              height: "25px",
              borderRadius: "15px",
              marginRight: "10px"
            }}
            src={character.avatar}
          />{" "}
          <span style={{ color: "navyblue" }}>{character.name}</span>
        </div>
      );
    },
    /**
     * This is what the <input/> value is set to when you are selecting a suggestion.
     */
    getSuggestionValue(suggestion) {
      return suggestion.item.name;
    },
    focusMe(e) {
      console.log(e)
    }
  }
};
</script>

For more advanced usage, check out the examples below, and explore the properties you can use.

Prop Type Required Description
suggestions Array โœ“ Suggestions to be rendered.
input-props Object โœ“ Add props to the <input>.
section-configs Object Define multiple sections <input>.
render-suggestion Function Tell vue-autosuggest how to render inside the <li> tag.
get-suggestion-value Function Tells vue-autosuggest what to put in the <input/> value

inputProps

Prop Type Required Description
id String โœ“ id attribute on <input>.
on-input-change Function โœ“ Triggers everytime the <input> changes. This is triggered via a Vue watcher, so you have both current value, and previous value access e.g. onInputChange(text, oldText)
onClick Function Deprecated Triggers everytime the <input> is clicked. You can now use @click which will map to the underlying <input />
onBlur Function Deprecated HTML onblur event on <input> same as Vue @blur event binding. You can now use @blur which will map to the underlying <input />
onFocus Function Deprecated HTML onfocus event on <input> same as Vue @focus event binding You can now use @focus which will map to the underlying <input />
initial-value String Set some initial value for the <input>.
Any DOM Props * You can add any props to <input> as the component will v-bind inputProps. Similar to rest spread in JSX. See more details here: https://vuejs.org/v2/api/#v-bind. The name attribute is set to "q" by default.

sectionConfigs

Multiple sections can be defined in the sectionConfigs prop which defines the control behavior for each section.

Prop Type Required Description
on-selected Function โœ“ Determine behavior for what should happen when a suggestion is selected. e.g. Submit a form, open a link, update a vue model, tweet at Ken Wheeler etc.
type String Vue component name for specifying which type to implement using Vue's <component :is="componentName"></component> functionality. See DefaultSection.vue for scaffolding a new type. You must declare your component in the scope of the app using Vue.component(). You can extend DefaultSection using extends. See UrlSection for an example.
limit Number Limit each section by some value. Default: Infinity

Below we have defined a default section and a blog section. The blog section has a component type of url-section which corresponds to which component the Autosuggest loads. When type is not defined, Vue-autosuggest will use a built in DefaultSection.vue component.

sectionConfigs: {
    'default': {
        limit: 6,
        onSelected: function(item, originalInput) {
            console.log(item, originalInput, `Selected "${item.item}"`);
        }
    },
    'blog': {
        limit: 3,
        type: "url-section",
        onSelected: function() {
            console.log("url: " + item.item.url);
        }
    }
}

renderSuggestion

This function will tell vue-autosuggest how to render the html inside the <li> tag. If you're not using babel-plugin-transform-vue-jsx then this method won't be too beneficial, but if your data is a list of objects you can return a specific object.

renderSuggestion(suggestion) {
    return <div style={{ color: "red" }}>{suggestion.name}</div>;
},

or if you don't use babel or the JSX transform, you can just return the specified object property.

renderSuggestion(suggestion) {
    return suggestion.name;
},

getSuggestionValue

This function will tell vue-autosuggest what to put in the <input/> as the value.

getSuggestionValue(suggestion) {
    return suggestion.name;
},

FAQ

How do I update the input programatically?

  • You can assign a ref to the component <vue-autosuggest ref="myRefName" ... /> and then access the input value through this.$refs.myRefName.searchInput. This is useful mainly for clearing the input. โš ๏ธ Note, refs are more of an "escape hatch" as they call it, so it won't trigger the onInputChange method.

Inspiration

Contributors

Thanks goes to these people (emoji key):


Darren Jennings

๐Ÿ’ป ๐Ÿ“– ๐Ÿš‡ โš ๏ธ ๐ŸŽจ ๐Ÿ’ก

Evgeniy Kulish

๐Ÿ’ป ๐ŸŽจ ๐Ÿ’ก โš ๏ธ

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

MIT

vue-autosuggest's People

Contributors

darrenjennings avatar ekulish avatar philipzaengle avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.