javascript - 当 Google Places API 自动完成授权失败时,输入会被禁用
问题描述
将 Google Places API 自动完成功能与 Vue/Vuetify 一起使用时,如果 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>
视图:
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
})
}
}
})
解决方案
我让它工作,但它有点hacky。首先,我在 中添加了一个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>
视图:
<script>
window.gm_authFailure = function() {
return false
}
[...]
mounted() {
window.gm_authFailure = function() {
document.getElementById('billingautocomplete').disabled = false
document.getElementById('billingautocomplete').placeholder = ''
}
[...]
推荐阅读
- javascript - 如何在反应中向左拉 1 个按钮,向右拉 2 个按钮>
- stripe-payments - Stripe iOS SDK via Swift Package Manager 正在安装,但由于“库未加载”而崩溃
- debugging - 为什么我不能命名无符号变量 v+digit?
- html - 动画 ::before 和 ::after
- node.js - Webpack 不排除排除数组中指定的文件
- python - 每个项目的 Django NodeNotFoundError
- javascript - 如何从 datepicker jQuery UI 中检索选定的日期值以触发某些事情
- java - 如何在相机屏幕上实现/制作 listView?
- javascript - HTML & React JS:CSS 设计位置问题。(内容卡在角落里)
- laravel - 如何在单元测试中将模型绑定到请求