GithubHelp home page GithubHelp logo

v-autocomplete's Introduction

v-autocomplete


Autocomplete component for Vue.js

This component is css-free. The idea is to be used with any framework.

Installation

Using yarn

yarn add v-autocomplete

Using npm

npm i --save v-autocomplete

Demo

DEMO

Usage

Bundler (Webpack, Rollup)

import Vue from 'vue'

import Autocomplete from 'v-autocomplete'

// You need a specific loader for CSS files like https://github.com/webpack/css-loader
import 'v-autocomplete/dist/v-autocomplete.css'

Vue.use(Autocomplete)

Browser

<!-- Include after Vue -->
<link rel="stylesheet" href="v-autocomplete/dist/v-autocomplete.css"></link>
<script src="v-autocomplete/dist/v-autocomplete.js"></script>
<script>
  Vue.use(VAutocomplete.default)
</script>

Example

<template>
  <v-autocomplete :items="items" v-model="item" :get-label="getLabel" :component-item='template' @update-items="updateItems">
  </v-autocomplete>
</template>

<script>
import ItemTemplate from './ItemTemplate.vue'
export default {
  data () {
    return {
      item: {id: 9, name: 'Lion', description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'},
      items: [],
      template: ItemTemplate
    }
  },
  methods: {
    getLabel (item) {
      return item.name
    },
    updateItems (text) {
      yourGetItemsMethod(text).then( (response) => {
        this.items = response
      })
    }
  }
}
</script>

ItemTemplate example:

<template>
  <div>
    <b>#{{item.id}}</b>
    <span>{{ item.name }}</span>
    <abbr>{{item.description}}</abbr>
  </div>
</template>

<script>
export default {
  props: {
    item: { required: true },
    searchText: { required: true }
  }
}
</script>

Properties

Name Type Required Default value Info
items Array Yes List items
component-item Vue Component or Function or String No Item Item list template
min-len Number No 3 Min length to trigger the updateItems event
wait String No 500 Miliseconds dela to trigger the updateItems event
get-label Function No function(item) { return item } Anonymous function to extract label of the item
value Mixed No Initial value (use v-model)
auto-select-one-item Boolean No true Auto select item if result one item in items
input-attrs Object No {} Attributes for input
keep-open Boolean No false If true, suggestions list stays open even when input is not active
placeholder String No Deprecated, will be removed in the next version. Use input-attrs
input-class String No Custom class of input search. Deprecated, will be removed in the next version. Use input-attrs
disabled Boolean No false Disable input. Deprecated, will be removed in the next version. Use input-attrs

Events

Name Params Info
input item: Item changed Triggered after any changed in the model
change text: Text of search input Triggered after every change in the search input
update-items text: Text of search input Same as change, but respecting min-len and wait
item-clicked item: Item clicked Triggered after a click on a suggestion
item-selected item: Item selected Like @input, but only when has value
blur text: Text of search input Triggered on blur in the search input
focus text: Text of search input Triggered on focus in the search input

What about appearence?

Just overwrite their css classes. See the structure in stylus lang:

.v-autocomplete
  .v-autocomplete-input-group
    .v-autocomplete-input
  .v-autocomplete-list
    .v-autocomplete-list-item
      &.v-autocomplete-item-active

Follows the css used in the DEMO:

.v-autocomplete
  .v-autocomplete-input-group
    .v-autocomplete-input
      font-size 1.5em
      padding 10px 15px
      box-shadow none
      border 1px solid #157977
      width calc(100% - 32px)
      outline none
      background-color #eee
    &.v-autocomplete-selected
      .v-autocomplete-input
        color green
        background-color #f2fff2
  .v-autocomplete-list
    width 100%
    text-align left
    border none
    border-top none
    max-height 400px
    overflow-y auto
    border-bottom 1px solid #157977
    .v-autocomplete-list-item
      cursor pointer
      background-color #fff
      padding 10px
      border-bottom 1px solid #157977
      border-left 1px solid #157977
      border-right 1px solid #157977
      &:last-child
        border-bottom none
      &:hover
        background-color #eee
      abbr
        opacity 0.8
        font-size 0.8em
        display block
        font-family sans-serif

Development

$ git clone https://github.com/paliari/v-autocomplete.git
$ cd v-autocomplete

Using yarn

# install dependencies
$ yarn install

# compile demo for development
$ yarn dev

# open Browser and start serve in demo
$ yarn demo:open

# compile dist demo
$ yarn dist:demo

# compile dist
$ yarn dist

Using npm

# install dependencies
$ npm install

# compile demo for development
$ npm run dev

# open Browser and start serve in demo
$ npm run demo:open

# compile dist demo
$ npm run dist:demo

# compile dist
$ npm run dist

Authors

License

This project is licensed under MIT License

v-autocomplete's People

Contributors

dependabot[bot] avatar dflourusso avatar dsanders11 avatar gabrielrobert avatar lon9 avatar mokkabonna avatar olimart avatar paliari avatar paulgv avatar rayrutjes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

v-autocomplete's Issues

Back space will remove selected item

The current behavior is that after an item is selected, if I hit backspace key, the whole selection is removed, instead remove the last letter of the label.

Is there a way to configure this behavior? I need to remove the last letter, not the whole selection string. Thanks!

reset v-autocomplete programatically

Hello

Can you please also add support for reset component programmatically.
currently I'm using following way to reset component.

<v-autocomplete ref="auto-complate" placeholder="Search customer" :items="items"
:get-label="getLabel" :auto-select-one-item="false" :component-item='template'></v-autocomplete >

this.$refs['auto-complate'].searchText = "";
this.items = [];

data has this type of array:

items: [
  {first: "Item", last: "A"},
  {first: "Item", last: "B"},
  {first: "Item", last: "C"},
  {first: "Item", last: "D"},
] 

and
getLable method returns:

getLabel(item) {
  item.first + ' ' + item.last;
},

setting items all the time with [] (null array) and searchText with "" (empty string). so end user have to type again for new item.

No text returned on update-items event in Android browsers

My implementation works perfectly except for in Chrome and Firefox on an Android device (Pixel 2). The update-item event is triggered but that text argument is blank. I keep running into this issue even with a basic implementation removing all functionality outside of v-autocomplete. The only place I see it working as expected is within your DEMO. Have you run across this issue in the past? Thank you

Make More Easy to Use :component-item

I'm trying to use :component-item property for five days, and it's very hard. I'm not using .vue files with components, but in a js file creating the components, the search i got it, but to show the results of search in two lines I didn't got. Please, make it easier to use, maybe allowing put the html (with text interpolation) in the: component-item property or another property, or calling a function that returns createElement array, or array of JSON object with a html property in every node, without having to use two components. After five days, second component (ItemTemplate) still doesn't work, it neither starts!, and the result of the search is working, but is showed like JSON.
Please, make more easy to show the result of the search in html (two lines , title in bold above and description bellow the title.

First Example to Make It Easer (HTML on :component-item or another property) :

var searchMenu=Vue.component("spsearchmenu",{
	name:"spsearchmenu",            
	components:{"v-autocomplete":VAutocomplete.default},
	template:'',
	data()  {
		return {
		  item: "",
		  items: []
		}
	},
	methods: {                
		getLabel(item){
		   return item ? (item.name ? item.name : "") :"";
		},
		updateItems(text) {
			text=text.toLowerCase();
			this.$data.items = text ? menuList.filter(function(menu) {
				return ( (menu.name.toLowerCase().includes(text)) || (menu.description.toLowerCase().includes(text)) )
			}) : menuList;
			
		}
	}
});

Second Example to Make It Easer (createElemnt on :component-item or another property) :

var searchMenu=Vue.component("spsearchmenu",{
	name:"spsearchmenu",            
	components:{"v-autocomplete":VAutocomplete.default},
	template:'',
	data()  {
		return {
		  item: "",
		  items: []
		}
	},
	methods: {                
		getLabel(item){
		   return item ? (item.name ? item.name : "") :"";
		},
                createArrayElements(){
                         var arrayCreateElements=[];  
                        // programmer do your magic here to fill Array
                       return arrayCreateElements;
                },
		updateItems(text) {
			text=text.toLowerCase();
			this.$data.items = text ? menuList.filter(function(menu) {
				return ( (menu.name.toLowerCase().includes(text)) || (menu.description.toLowerCase().includes(text)) )
			}) : menuList;
			
		}
	}
});

Third Example to Make It Easer (JSON with specific properties on :component-item or another property) :
properties:
id: identifier to node and select operation
title: short text showed for user to select (in bold)
description: large text describing the item

var searchMenu=Vue.component("spsearchmenu",{
	name:"spsearchmenu",            
	components:{"v-autocomplete":VAutocomplete.default},
	template:'',
	data()  {
		return {
		  item: "",
		  items: []
		}
	},
	methods: {                
		getLabel(item){
		   return item ? (item.name ? item.name : "") :"";
		},
                createJSONArray(){
                        // programmer do your magic here to fill Array
                         //example of JSON
                         var arrayJSON=[
                                 {id:1,title:"Open",description:"Open a new file"},
                                 {id:2,title:"Save",description:"Save current file"},
                               ];  
                       return arrayJSON;
                },
		updateItems(text) {
			text=text.toLowerCase();
			this.$data.items = text ? menuList.filter(function(menu) {
				return ( (menu.name.toLowerCase().includes(text)) || (menu.description.toLowerCase().includes(text)) )
			}) : menuList;
			
		}
	}
});

Can't set empty value

Hello.
In my project i need to unset selected values and clear inputs, but something goes wrong, model in component behaves like non reactive variable.

If i try to set empty value to model, input ignore it, but work if i set non empty value.

In fiddle select some value, then push "Set empty value", you will see model become empty but not input.

https://jsfiddle.net/196e7sr9/

Also i think "min-len" option doesn't work, in example trigger fires when i write only one symbol.

only one match

when only one matched, it auto fill input field, i want not, can you make a switch?

v-autocomplete-item not set to active on hover

When hovering over an item in the list the class is not set to active, meaning when styling the element you have to do something like:
.v-autocomplete .v-autocomplete-list .v-autocomplete-list-item:hover{ background-color:#a488a5; color:white; cursor: pointer; }

If you are hovering over an element with the mouse and then use the keyboard to navigate the list you end up with a :hover style and a style on the active element like so:
.v-autocomplete .v-autocomplete-list .v-autocomplete-list-item.v-autocomplete-item-active{ color:white; background-color:#a488a5; }
Resulting in it looking like two things are selected. I'd suggest making the class active on the element you are hovering over.

Equally happy to be show another way to do this.
Thanks

Source will be overwritten after search

After you enter the search text, the source array got overwritten with search result. Is it a bug?

update (text) {
this.items = Animals.filter((item) => {
return (new RegExp(text.toLowerCase())).test(item.name.toLowerCase())
})
}

Event on input focus

Hello, thanks for great plugin.

Got question, beacuse i can't find it in documentation:
Is there a way to trigger event when input is focused?

Thanks

Scroll in browser.

When I press Up OR Down arrow browser gets scroll to selected item in list.
I do not know this is feature or not. But if we can handle this it will better.

Event keyup

Hi thanks a lot for this wonderful module :)
Is possible to add @keyup event on input search ?

<v-autocomplete :items="items" :get-label="getLabel" :component-item='template' :min-len="1"
                          :input-attrs="{ id: 'newTag', placeholder: 'Rechercher par mot clés' }" @update-items="updateItems" @keyup="keyupAction">

In fact, i need to add the possibility to do a specific action on "enter" key.
Best regards.

keep-open property is ignored on empty items list

Hi,

The keep-open property is in fact not working in case when items is an empty array: the list element is removed from the DOM, but it should not.

This breaks my UX since this list is always open and has fixed height. In case when user enters text which results in empty result list, list is removed from DOM and there occurs an unpleasant snapping in interface.

How do I use this with Vuex?

I'm having trouble figuring out how to use this with vuex...

I was trying to use the item-selected event:

file.vue

<template id="search-template">
      <v-autocomplete
      v-bind:items="items"
      v-bind:min-len='2' 
      v-bind:get-label="getLabel" 
      v-bind:component-item="template"
      v-model="selectedItem" 
      v-on:update-items="updateItems"
      v-on:item-selected="setActiveCarInfo">
      </v-autocomplete>
</template>
<script src="./file.js">

export default{
}
</script>

file.js

export default {
  data () {
    return {
      selectedItem: [],
      items: [],
      template: TypeAhead,
    }
  },
  components: {
    'CarSearch': TypeAhead
  },
  methods: {
    getLabel (item) {
      return item.carName
    },
    updateItems (text) {
      axios.get('http://somehost/api/car/lookup/' + text).then((response) => {
        this.items = response.data
      },
        (error) => {
          console.log(error)
        })
    },
    ...mapActions(['setActiveCarInfo']),
  }
}

store.js (for vuex)

const state = {
  initialArray: [],
  activeVarInfo: null
}

const actions = {
  setActiveCarInfo: (context,carId) => {
    return axios.get('http://somehost:api/car/info/' + carId)
        .then((response) => context.commit('SET_ACTIVE_CAR', response.data))
        .catch((error) => context.commit('API_FAILURE', error))
    }
  }

// define the possible mutations that can be applied to our state
const mutations = {
  SET_ACTIVE_CAR (activeCarInfo) {
    console.log("Setting active car in state management")
    state.activeCar = activeCarInfo
    
  },
  API_FAILURE(error){
    console.log("In API Failure")
    console.log(error)
  }
}

const getters = {
  activeCarInfo: state => state.activeCarInfo
}

// create the Vuex instance by combining the state and mutations objects
// then export the Vuex store for use by our components
export default new Vuex.Store({
  state,
  actions,
  getters,
  mutations
})

It looks like the SET_ACTIVE_CAR ends up with a payload for the entire list on the initial page load which is 5000+ items instead of the one I want.
How do I bind to a single selected item?

Thanks

First keystroke doesn't register

When entering input, the first keystroke never registers and the input remains empty. Only subsequent keystrokes are counted.

Example:

  1. Open this fiddle (taken from another issue): https://jsfiddle.net/196e7sr9/
  2. Try to type in the box

You'll notice that your first keystroke isn't counted. This occurs in both Firefox and Chrome.

How to enable keyboard on select items

Hi!
This really is a great component. But is there a way to use the keyboard when the list is displayed? instead of clicking, just selecting it with the arrow key
Thanks!

If the user don't select a choice

Hi,

I use your plugin to propose to visitors to choose a clothes brand. Everything work well if the visitor choose a brand in the list. But sometimes he does not find what he wants.

The problem is that the v-model don't returning the searchText value.

So, if the autocomplete don't return what the user want, the value he wrote must be saved.

How do you do that?

Thanks for your work.

On pug and stylus

Hey Guys,

Thanks for the component. I really like it! Especially the simplicity.

I have a more theoretical consideration. Is it necessary for you to use pug and stylus? The code for the component is not very long and just to experiment a bit on the forked version you need to set up pug and stylus locally. I know it is your component and you can use whatever you wish, but wouldn't it be easier to stick to plain HTML and CSS?

For example, I added the 'name' attribute (which is now missing, but can be useful for form submits) to the component in my fork and can't really do a PR, since I 'translated' the pug and stylus code (doesn't make sense to include those dependencies in my project).

I just would like you to give it a little thought :)

Set input id

How can I set an id for the input this creates? and a name?

No Records Found

Hi,

If there is no match according to my search key then how could I show 'No Records Found' or something relevant to this.

Thanks.

Option to add CSS class to input element

I'm using the Bulma CSS library and would like to be able to add a .input class to the inner input element of the autocomplete. Ideally, it would be great if v-autocomplete exposed a property that allowed a class to be added to the inner input element.

Thanks :)

How can I add bootstrap class to the tags?

Hi,

I am a newbies.
I just want to ask how can I integrate this project into bootstrap4.
e.g. using bootstrap4-dropdowns to style the .v-autocomplete-list

Thank you very much

Unexpected behavior on keyup

Hi,

I'm not sure if i'm making some mistake but I'm following the demo code.
The problem that I'm having is that the method getLabel gets called twice the first time, one time with undefined parameter and the second time it is called with the correct word that I just typed.

The problem in consequence is that for example, I type the word: abcd, then the field is cleared and only bcd is applied.

The difference in my code is that my template is not an object but a string, as follows:

<template>
  <div>
    <span>{{ item }}</span>
  </div>
</template>

<script>
export default {
  props: {
    item: { required: true }
  }
};
</script>

and my getLabel method is as follows:

getLabel(item) {

  if (item) {
    return item;
  }
  return '';

}

One important thing is that I don't want the field to be initialized. The demo example initializes the field with some object, then you have to delete the current word and then everything works as expected.

To reproduce the error leave the item as an empty object or an empty string.

export default {
  name: 'demo',
  components: {'v-autocomplete': Autocomplete},
  data () {
    return {
      itemsApi: [],
      item: {},
      items: [],
      tpl: tpl
    }
  }
}

Thanks

FeatureRequest: Clear on select

Would it be possible to clear the input when selecting an item?
Cannot find any option for this behaviour so I assume it's not implemented.
Would it be possible to modify the value of the v-autocomplete component outside of the component?

v-autocomplete not working with array.

Hello,

I'm requesting you to add feature for array support. I'm using v-autocomplete 5 or more time in my application.
As per current behavior v-autocomplete works very good with String Array
["Item A", "Item B", "Item C", "Item D", "Item E", "Item F", "Item G", "Item H"],

but not with:

[
  {first: "Item", last: "A"},
  {first: "Item", last: "B"},
  {first: "Item", last: "C"},
  {first: "Item", last: "D"}
]

Every time I have to convert Array of object to Array of string.

min-length property off by one

The docs say:
min-len : Min length to trigger the updateItems event

<v-autocomplete :items="items" :min-len='2' v-model="item" :get-label="getLabel" :component-item='template' @update-items="updateItems"> </v-autocomplete>

I would be expecting the update to occur after the second character was entered, currently it seems to do it on n+1 character.

Search input is not empty after reset the item-list

Hi,

I need to clear the search text after a user clicked on 'Add' button.

addUser: function() {
    this.group.users.push(this.selectedUser);
    this.selectedUser = '';
    this.userList = [];
},
<v-autocomplete :items="userList" v-model="selectedUser" :id="selectedUser" :wait="100" :get-label="getLabel" :min-len=3 placeholder="Search User" :input-class="'form-control'" :component-item="template" @update-items="updateItems"></v-autocomplete>

How is it possible?

Item Selected doesn't always run when the page is created

I am trying to figure out what is wrong with the populating initial value. Whenever I navigate to the page with autocomplete, v-model/value should give the initial value for the input field. However, I am not seeing this behavior. I have put v-model="local_id" where local_id is the initial text that is given to the component. I cannot see the initial value every time even though local_id has an initial value. Whenever I switch between pages and come back to Autocomplete page, it only gets the label sometimes.

When I checked, it looks like my get-label and item-selected don't run every time I go to the page.

Input deleted after having one item selected

You can see this behaviour in the DEMO. It starts with one item selected. If you want to add any character, the input is deleted. this happens every time you have one item selected.
I your code starts with empty item, the first character is ignored.

1.6.0 Webpack Errors

After upgrading from 1.6.0 I get the following from webpack:

[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.
found in
---> at src\components\TopsPortfolios.vue
at src\App.vue

This is the current initialization that works fine for 1.5.3 but breaks for 1.6.0
`import Vue from 'vue'
import App from './App'
import router from './router'
import BootstrapVue from 'bootstrap-vue'
import Autocomplete from 'v-autocomplete'
import 'v-autocomplete/dist/v-autocomplete.css'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'

Vue.config.productionTip = false
Vue.use(BootstrapVue)
Vue.use(Autocomplete)

/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '',
components: { App, BootstrapVue, Autocomplete }
})`

Is there anything else I can provide?
End result is no autocomplete box and broken rest of the app.

consider using `input[type=text]` or allow to override

Hi! Thanks for the package 👍
Styling the input requires -webkit-appearance: textfield, or none. I see that you use it in the demo CSS, but this is not documented.

Also, type=search has a special meaning; for example, I get suggestions from my contacts on OS X. This is not what I want, and I assume most people do not want this either. Rather, suggestions should only be from the items attribute.

Changing input type to text will solve all above.

Expand items on first click

Hi,

Many thanks for this nice component.

I am using it with "min-len" = "0" because I want to expand the items right after clicking on it. This feature seems to work only after typing something, then emptying the search box and clicking again. It does not expand the items on the first click.

Any idea on how to expand items on first click?

Min-len Number required error

Can the value for Minlength be parsed to an integer before throwing the error

vue.esm.js?65d7:558 [Vue warn]: Invalid prop: type check failed for prop "minLen". Expected Number, got String. 

As there is no way you can specify attribute value without the "" in html. Setting the Min length value gives the above error whether directly or via a component property

:input-attrs="{'class':'form-group'}" not working

HI,

I tried adding this several times but the input is not picking up the class.

:input-attrs="{'class':'form-group'}"

I also tried

input-attrs="{'class':'form-group'}"

image

Source code:
image

Dev tools output:

image

Any advice?

Thank you

Overlay the drop down

@paliari Thanks for this plugin. one issue though, can you make the dropdown of filtered result overlay the content below the component instead of displacing them , like other select components behave

Min-len not working

Latest version.

Apply attribute min-len, set value to "1". Error in Chrome dev tools.

Invalid prop: type check failed for prop "minLen". Expected Number, got String.

Markup:
<v-autocomplete :items="filteredUsers" min-len="1" placeholder="Enter name or email" v-model="selectedUser" :get-label="getLabel" :component-item='template' @update-items="updateItems"></v-autocomplete>

Clear filter does not work in Firefox

Hi,

I experienced that the onKeyup listener for esc is not working for clearing the filter in firefox.
I experienced that in my application but afterwards i realized that I happens at the demo page too.

I tested in firefox quantum and I'm using a Mcbook Air

Thanks!

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.