问题描述
在通过Vue / Vuetify使用Google Places API自动完成功能时,如果API脚本未授权,则文本字段将被禁用,并且第一个字符后将不允许进一步输入。
如何使它在后台安静地失败并允许输入文本?
我知道这里有gm_authFailure()
,如果发生故障,Places API将在全局调用它,但是我不确定如何允许该函数在Vue中调用它。
JSfiddle:https://jsfiddle.net/wya72b0j/
HTML:
<div id="app">
<v-app>
<v-container class="ma-auto pa-auto blue-grey darken-4 fill-height">
<v-row justify="center" class="mx-5 px-5">
<v-text-field
v-model="billingAddress"
@focus="billingAutocomplete()"
required
ref="billautocomplete">
</v-text-field>
</v-row>
</v-container>
</v-app>
</div>
Vue:
new Vue({
el: "#app",vuetify: new Vuetify({
theme: {
dark: true,}
}),data: () => ({
billingAddress: '',}),mounted() {
const placesapi = document.createElement('script')
placesapi.setAttribute(
'src','https://maps.googleapis.com/maps/api/js?key=ThisKeyNotDoesNotWork&libraries=places'
)
document.head.appendChild(placesapi)
},methods: {
billingAutocomplete() {
let addressArray = {
street_number: '',route: '',locality: '',administrative_area_level_1: '',country: '',postal_code: '',}
let element = this.$refs.billautocomplete.$refs.input
const google = window.google
let autocomplete = new google.maps.places.Autocomplete(element,{
types: ['geocode'],componentRestrictions: {
country: 'us'
},})
autocomplete.setFields(['address_component'])
autocomplete.addListener('place_changed',() => {
const componentForm = {
street_number: 'short_name',route: 'long_name',locality: 'long_name',administrative_area_level_1: 'short_name',country: 'long_name',postal_code: 'short_name',}
let place = autocomplete.getPlace()
for (const component of place.address_components) {
const addresstype = component.types[0]
if (componentForm[addresstype]) {
const val = component[componentForm[addresstype]]
addressArray[addresstype] = val
}
}
this.billingAddress = addressArray
})
}
}
})
解决方法
我可以使用它,但是有点笨拙。首先,我在id
上添加了v-text-field
标签,以防止被禁用的空白占位符。在<script>
标签下,我在一个基本为空的函数中添加了window.gm_authFailure()
,最后在mounted
下,添加了处理禁用输入的实函数。我敢肯定有更好的/正确的方法,但这行得通。
更新的JSFiddle:https://jsfiddle.net/90ua3xzy/
HTML:
<v-text-field
v-model="billingAddress"
@focus="billingAutocomplete()"
required
ref="billautocomplete"
id="billingautocomplete">
</v-text-field>
Vue:
<script>
window.gm_authFailure = function() {
return false
}
[...]
mounted() {
window.gm_authFailure = function() {
document.getElementById('billingautocomplete').disabled = false
document.getElementById('billingautocomplete').placeholder = ''
}
[...]