如何使用谷歌自动完成功能在 vue.js 中设置多个字段?
2019-06-21
1419
我尝试使用 Google 自动完成功能在 vue.js 文件中通过单一选择填写多个字段。我从哪里获取 address_components? vue-google-autocomplete 来自这里: https://github.com/olefirenko/vue-google-autocomplete
到目前为止,我曾尝试遵循此处找到的相同谷歌地址表单: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
在控制台中,我收到此错误
TypeError: "e[s] is undefined"
对于 HTML 组件,我有:
<label >City</label>
<vue-google-autocomplete ref="locality" id="locality" class="form-control" type="text" v-on:placechanged="getAddressData" placeholder="Enter city" country="us"></vue-google-autocomplete>
</div>
<div class="col" style="margin-bottom: 20px;">
<label >State</label>
<vue-google-autocomplete ref="administrative_area_level_1" id="administrative_area_level_1" class="form-control" type="text" maxlength="2" v-on:placechanged="getAddressData" placeholder="Enter State" country="us"></vue-google-autocomplete>
</div>
<div class="col" style="margin-bottom: 20px;">
<label >Zip Code</label>
<vue-google-autocomplete ref="postal_code" id="postal_code" class="form-control" type="text" maxlength="5" v-on:placechanged="getAddressData" placeholder="Enter zip code"></vue-google-autocomplete>
</div>
到目前为止,我曾经能够获得 3 个字段来填充
Object object
以某种方式但我似乎无法重现它因为我已经改变了它。
return{
componentForm: {
street_number: '',
route: '',
locality: '',
administrative_area_level_1: '',
country: '',
postal_code: ''
}
}
getAddressData: function (addressData, placeResultData) {
for(var i = 0; i < placeResultData.address_components.length; i++) {
var addressType = placeResultData[i].types[0]
if(this.componentForm[addressType]) {
var val = placeResultData.address_components[i][this.componentForm[addressType]]
document.getElementById(addressType).value = val
}
}
}
我想获取多个字段来填充我返回的所有位置组件但我不确定为什么我的 getAddressData 没有设置各个组件的值。
1个回答
尝试以下操作:
getAddressData (event){
console.log(event);
if (event.address_components){
if (event.address_components[2].long_name) {
this.$el.querySelector('#locality').value = event.address_components[2].long_name; //Check from console
}
if (event.address_components[4].long_name) {
this.$el.querySelector('#administrative_area_level_1').value = event.address_components[4].long_name; //Check from console
}
}
}
注意
检查您需要哪些数据,我不确定名称。但我认为这应该可以正常工作并填充您的输入。
mare96
2019-06-21