【问题标题】:How to close autocomplete dropdown when clicked outside?在外部单击时如何关闭自动完成下拉菜单?
【发布时间】:2020-11-04 21:30:25
【问题描述】:

点击任何外部区域时如何关闭自动完成下拉菜单?目前我正在调用我的自定义自动完成组件(子演示组件)3次,使用来自另一个名为departmentDetail.vue的vue页面(父)的不同标签。

例子:

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(我创建的自定义组件)

<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>

部门屏幕截图

为什么有时页面加载时这些输入字段中没有显示值?但是在集中注意力或如果我输入任何内容时,值会突然出现?知道为什么会这样吗?

【问题讨论】:

    标签: html vue.js autocomplete


    【解决方案1】:

    关于你的最后一个问题: “为什么当页面加载时,有时这些输入字段中没有显示值?但是在焦点或如果我输入任何内容时,值会突然出现?知道为什么会这样吗?”

    您似乎在计算道具上使用 API 请求。 计算的道具是预渲染的值。如果您的 API 是异步工作的,那么在解析完整请求之前,计算结果会呈现为“空”。

    您可以尝试 data props 并在 Mounted() 或 Created() 中使用 API 设置器设置它们。

    编辑: 它可能看起来像这样:

        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; 
    
    
          
      },
    

    【讨论】:

    • 您好,感谢您的回复,但您可以给我一个使用我的代码的示例吗?
    • 如果你看到我在计算部分有以下方法 - viewData() { return this.$store.getters.getViewData('DepartmentDetail') }, objectData() { return this.$store .getters.getApiData(this.viewData.api_id).data
    • 好的,谢谢你的回复,我会试试你的建议。关于我的第一个问题的任何想法(点击任何外部区域时如何关闭自动完成下拉菜单)
    猜你喜欢
    • 1970-01-01
    • 2017-03-23
    • 2023-02-23
    • 1970-01-01
    • 2016-06-13
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多