vah*_*det 1 javascript autocomplete google-places-api vue.js vuetify.js
我尝试使用Google Places Autocomplete API来填充Vuetify Autocomplete 组件,如下所示:
<template>
<v-autocomplete
ref="autocomplete"
label="Location"
>
</v-autocomplete>
</template>
<script>
export default {
mounted() {
var autocomplete = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */(this.$refs.autocomplete),
{types: ['geocode']})
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
但是,在浏览器的开发者控制台中,却抛出了一个错误:
InvalidValueError: 不是 HTMLInputElement 的实例
我的猜测v-autocomplete不是HTMLInputElement类型。
(而且不仅是这种情况v-autocomplete:将其替换为v-input也会导致同样的错误。)
有没有办法让v-autocompleteGoogle Places Autocomplete API 充满,比如让它成为一个HTMLInputElement手动的实例?
看来双方保持材料的外观没有直接的方法v-autocomplete时,仅仅使用google.maps.places.Autocomplete。为了实现这一点,我包装了getPlacePredictions()API的方法 - 而不是一个组件 - 称为Autocomplete Service:
PlacesUtils.js
/* global google */
const GetSuggestions = async searchText => {
let result
try {
const rawResult = await searchLocation(searchText)
result = rawResult.map((res) => {
return {
id: res.place_id,
value: res.description
}
})
} catch (err) {
console.log('An error occurred', err)
result = null
}
return result
}
// Auxiliary functions
// wrap google api's callback to an async function
const searchLocation = async val => {
let promise = await new Promise((resolve, reject) => {
var displaySuggestions = (predictions, status) => {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
reject(status)
}
resolve(predictions)
}
var service = new google.maps.places.AutocompleteService()
service.getPlacePredictions({
input: val,
types: ['geocode']
},
displaySuggestions)
}).catch(function (err) { throw err })
return promise
}
export { GetSuggestions }
Run Code Online (Sandbox Code Playgroud)
然后,watch为v-autocomplete我在用户所做的更改时调用此方法的模型添加一个,如下所示:
地方.vue
<template>
<v-layout row justify-center>
<!-- ... -->
<v-autocomplete
label="Location"
v-model="autocompleteLocationModel"
:items="locationFoundItems"
:search-input.sync="locationSearchText"
item-text="value"
item-value="id"
hide-no-data
return-object
>
</v-autocomplete>
<!-- ... -->
</v-layout>
</template>
<script>
/* eslint handle-callback-err: "warn" */
import { GetSuggestions } from '@/utils/PlaceUtils'
export default {
data () {
return {
autocompleteLocationModel: null,
locationSearchText: null,
locationEntries: []
}
},
computed: {
locationFoundItems () {
return this.locationEntries
}
},
watch: {
locationSearchText (newVal) {
var _vue = this
// If less than 3 chars typed, do not search
if (!newVal || newVal.length <= 3) return
// Call the method from the previous section here
GetSuggestions(newVal)
.then(function (res) {
_vue.locationEntries = res
})
.catch(function (err) {
// error handling goes here
})
}
}
// ...
}
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2097 次 |
| 最近记录: |