[Vuejs]-Vue.js Autocomplete

0👍

This is what I came up with. Works nicely.

The View

<label>Vendor:</label>
<input type="text" v-model="vendor" v-on:keyup="get_vendors" class="col-xl-6 form-control ">
   <div class="panel-footer autocomplete-box col-xl-6">
      <ul class="list-group">
         <li v-for="(vendor,id) in vendors" @click="select_vendor(vendor)" class="list-group-item autocomplete-box-li">
            {{ vendor.vendor_name }}
         </li>
      </ul>
   </div>

The Script

 export default {
        data: function() {
            return {
                vendor:'',
                vendor_id:'',
                vendors: []
             }
        },
        methods: {
            select_vendor(vendor){
                this.vendor = vendor.vendor_name
                this.vendor_id = vendor.id
                this.vendors = [];
            },
            get_vendors(){
                if(this.vendor.length == 0){
                    this.vendors = [];
                }
                if(this.vendor.length > 0){
                    axios.get('search_vendors',{params: {vendor: this.vendor}}).then(response => {
                        this.vendors = response.data;
                    });
                }
            },

        },
    }
</script>

The Route

Route::get('search_vendors', 'vendorController@search_vendors');

The Controller

  public function search_vendors(Request $request){
        $vendors = vendor::where('vendor_name','LIKE','%'.$request->vendor.'%')->get();
        return response()->json($vendors);
    }
 

The CSS

.autocomplete-box-li:hover {
  background-color: #f2f2f2;
}
.autocomplete-box{
  position: absolute;
  z-index: 1;
}

0👍

If you want to get the id of the vendor you can do it using vendor.vendor_id which should be present in the vendor object which is returned from the server and if you want to populate the vendors array with new options you can have a watch or a @change (binding) function to add the entered text field as the new vendor in the vendor array. Also, I would suggest that you download the vue extension as it will help you a lot in debugging

<label>Vendor:</label>
   <input type="text" v-model="vendor" v-on:keyup="get_vendors">
       <div class="panel-footer" v-if="vendors.length">
            <ul class="list-group">
                <li class="list-group-item for="(vendor,index) in vendors">
                    {{ index }}
                    {{ vendor.vendor_id }}
                    {{ vendor.vendor_name }}
                </li>
            </ul>
       </div>

Leave a comment