ElementUI实现地址自动补全文本框

Logo

新冠疫情自我检测系统网页设计开发文档

Sylvan Ding 的第一个基于 Vue.js 的项目. 本项目所提供的信息,只供参考之用,不保证信息的准确性、有效性、及时性和完整性,更多内容请查看国家卫健委网站!
Explore the docs »

View Demo · Report Bug · Request Feature

homepage

ElementUI实现地址自动补全文本框

We use el-autocomplete component and inputTips API from lbs.amap, which helps realize the Query Autocomplete service. The Query Autocomplete can be used to provide a query prediction for text-based geographic searches, by returning suggested queries as you type. Note that you can only use this service 5,000 times per day. We set inputTipsOpen = false when the service reaches the limit or something wrong happens with API server.

开发环境

node 14.16.1
npm 8.18.0
vue-cli 2.9.6
vue 2.5.2

解决方案

<template>
  <el-autocomplete
    v-model="place"
    :fetch-suggestions="querySearchAsync"
    placeholder="请输入地址(省/市/地/县)"
    :trigger-on-focus="false"
    :clearable="true"
    prefix-icon="el-icon-place"
  ></el-autocomplete>
</template>

<script>
import request from '@/utils/request'
import { errorMsg, infoMsg } from '@/utils/msgsettings.js'
export default {
  data() {
    return {
      place: '',
      addresses: [],
      timeout: null,
      inputTipsOpen: true,
    }
  },
  methods: {
    querySearchAsync(queryString, cb) {
      this.addresses.splice(0, this.addresses.length)
      this.inputTips(queryString)
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        cb(this.addresses)
      }, 600)
    },
    inputTips(queryString) {
      // ! frequency limit: 5,000 times per day
      // https://lbs.amap.com/api/webservice/guide/api/inputtips
      request
        .request({
          url: '/inputtips',
          baseURL: 'https://restapi.amap.com/v3/assistant/',
          params: {
            keywords: queryString,
            datatype: 'poi',
            key: 'fdfb60635a50****298be7dc28',
          },
        })
        .then((response) => {
          var { status, info, tips } = response.data
          if (status === '1') {
            this.addresses = tips.map((value) => {
              // {value, id, name, district, adcode, location, address}
              return {
                value: `${value.district}${value.name}`,
                ...value,
              }
            })
          } else {
            if (this.inputTipsOpen) {
              errorMsg(info)
              this.inputTipsOpen = false
            }
          }
        })
        .catch(() => {})
    },
  },
}
</script>

转载请注明出处:©️ Sylvan Ding 2022

猜你喜欢

转载自blog.csdn.net/IYXUAN/article/details/127034928
今日推荐