How to close autocomplete dropdown when clicked outside?

How to close autocomplete dropdown when clicked on any outside area? Currently i am calling my custom autocomplete component(child presentation component) 3 times with different labels from another vue page(parent) called departmentDetail.vue.

Example:

departmentDetail.vue

<b-field label="Custom Business Unit ">     <AutoComplete :method="getAsyncDataBusinessUnit" title='businessUnit'   :autocompleteData="dataBusinessUnit" viewname='DepartmentDetail'>       </AutoComplete>  </b-field>     <b-field label="Custom Managers">     <AutoComplete :method="getAsyncData" title='manager'  :autocompleteData="dataManager" viewname='DepartmentDetail'>       </AutoComplete>      </b-field>    <b-field label="Custom Location">     <AutoComplete :method=" getAsyncDataLocation" title='location'  :autocompleteData="dataLocation" viewname='DepartmentDetail'>       </AutoComplete> </b-field>   

AutoComplete.vue (Custom component created by me)

<template>    <div class="autocomplete">     <input style="font-size: 12pt; height: 36px; width:1800px; " type="text"    v-model="objectData[title]" @focus="getAsyncDataBusinessUnit" @input="getAsyncDataBusinessUnit"/> <ul v-show="isFetching" >       <li v-for="(dataBusinessUnit, i) in dataBusinessUnit" :key="i" @click="setResult(dataBusinessUnit)" >                    <template v-if="title!='manager'">           <div class="container">             <p>               <b>ID:</b>               {{dataBusinessUnit.id}}             </p>             <p>               <b>Description:</b>               {{dataBusinessUnit.description}}             </p>           </div>         </template>          <template v-else>         <div class="container">             <p>               <b>ID:</b>               {{dataBusinessUnit.id}}             </p>             <p>               <b>First Name:</b>               {{dataBusinessUnit.firstName}}             </p>             <p>               <b>Last Name:</b>               {{dataBusinessUnit.lastName}}             </p>           </div>         </template>            </li>     </ul>   </div> </template>   <script> import { viewMixin } from "../viewMixin.js"; import schemaData from '../store/schema'; import debounce from "lodash/debounce"; import api from "../store/api"; const ViewName = "AutoComplete"; var passedview;  export default {   name: "AutoComplete",    props: {     method: {          type: Function          },         title: String,         viewname:String,         autocompleteData: {        type: Array,        required: true     }   },        data() {     return {   //   results: [],       dataBusinessUnit: [],       results: [],       isFetching: false      // vignesh: this.objectData[this.title]     };   },    computed: {             viewData() {                 return this.$store.getters.getViewData('DepartmentDetail')             },             objectData() {                                return this.$store.getters.getApiData(this.viewData.api_id).data             },             sessionData() {                 return this.$store.getters.getSessionData()             },             isLoading() {                 return this.$store.getters.getApiData(this.viewData.api_id).isLoading             },             newRecord() {                 return this.$route.params.id === null;             },             getTitle() {               return this.title             }               },      mounted() {                },     methods: {        setResult(result) {                  this.updateValue(result.id,this.title);         //  localStorage.setItem(this.title,result.id );                  this.isFetching = false;       },           updateValue(newValue, fieldName) {                 var val;                  var schema = schemaData[this.viewData.schema];                                  if(typeof schema!=='undefined' && schema['properties'][fieldName]['type'] == 'date'){                     val = this.formatDate(newValue);                 } else {                     val = newValue;                 }                                  this.$store.dispatch('updateDataObjectField', {                     key: this.viewData.api_id,                     field: fieldName,                     value: val                 });             },   getAsyncDataBusinessUnit: debounce(function(name) {                      console.log('getAsyncDataBusinessUnit you typed'+name.target.value);       if (!name.target.value.length) {        // this.results = [];        // this.dataBusinessUnit = [...this.results];       //  this.isFetching = false;        // return;       }    //   this.isFetching = true;               api          .getSearchData(this.sessionData.key,`/businessunit/`,{ filter: `{id}like'%${name.target.value}%'` })             .then(response => {           this.results = [];           if (!response.length)           {             console.log('inside if ')           this.isFetching = false;           }            else{             console.log('inside else')             response.forEach(item => {             this.results.push(item);           });          // this.dataBusinessUnit=this.results           this.dataBusinessUnit = [...this.results];           this.isFetching = true;           }                     console.log('length of dataBusinessUnit is '+(this.dataBusinessUnit).length)           console.log('contents of dataBusinessUnit array '+JSON.stringify(this.dataBusinessUnit))         })         .catch(error => {           //this.dataBusinessUnit = [];           throw error;         })         .finally(() => {          // this.isFetching = true;         });      }, 500),             },          components: {           }  }; </script>  

Screenshot of the Department screen

Department page screenshot And why is it that when the page loads sometimes the values dont show up in these input fields? But upon focus or if i type anything then sudddenly the value shows up?Any idea why this is happening?

Add Comment
1 Answer(s)

About your last question: "And why is it that when the page loads sometimes the values dont show up in these input fields? But upon focus or if i type anything then sudddenly the value shows up?Any idea why this is happening?"

It looks like you are usesing API requests on computed props. Computed props are pre renderd values. If your API works async then the computed is renderd "empty" before the full request is resolved.

you could try data props and set them with the API setter in Mounted() or Created().

EDIT: It could look something like this:

    data() {     return {   //   results: [],       dataBusinessUnit: [],       results: [],       viewData: [],       objectData:[],       sessionData:[],       isLoading: [],       isFetching: false      // vignesh: this.objectData[this.title]     };   },    computed: {                         newRecord() {                 return this.$route.params.id === null;             },             getTitle() {               return this.title             }               },      mounted() {      this.viewData = this.$store.getters.getViewData('DepartmentDetail');      this.objectData = this.$store.getters.getApiData(this.viewData.api_id).data;  this.sessionData = this.$store.getters.getSessionData(); this.isLoading = this.$store.getters.getApiData(this.viewData.api_id).isLoading;             }, 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.