我通常使用 ref
关键字来访问 vue 中的组件。但我似乎不明白如何从组件中访问 HTML 标记。
我试过:
<input type="text" ref="searchAddress" id="searchAddress" name="searchAddress" class="form-control" v-model="incidentForm.searchAddress">
在 vue 组件中:
var input = this.$refs.searchAddress;
但这不起作用,所以我假设它只在引用组件时起作用?我如何从 vue 中访问输入标签?
我创建了一个类来管理所有将包含在我的 Vue 文件中的 GoogleMaps Api 调用。因此,我看不出有什么办法可以处理访问特定输入字段的数据。避免像这样直接访问的正确方法是什么?
完整的代码示例和更具体的:
GoogleMaps 的自动完成功能没有像我期望的那样返回任何内容。 未捕获的类型错误:无法设置未定义的属性“autocompletePlace”
。 this.autocompletePlace = place
似乎不起作用。
methods: {
initMap: function initMap() {
this.initialLocation = this.createInitialLocation(48.184845, 11.252553);
this.mapSetup(this.$refs.map, this.initialLocation, function () {
this.initAutoCompleteListener(function (place) {
this.autocompletePlace = place;
});
}.bind(this));
}
}
GoogleMapsApi.js
export default {
data() {
return {
map: '',
currentIncidentLocation: '',
autocomplete: '',
searchMarker: ''
}
},
events: {
currentIncidentLocation: function(location) {
this.currentIncidentLocation = location;
}
},
methods: {
createInitialLocation: function(latitude, longitude) {
return new google.maps.LatLng(latitude, longitude);
},
mapSetup: function(selector, initialLocation, callback) {
this.map = new google.maps.Map(selector, {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
this.map.setCenter(initialLocation);
this.searchMarker = this.createMarker();
var input = document.getElementById('searchAddress');
this.autocomplete = new google.maps.places.Autocomplete(input);
callback();
},
initAutoCompleteListener: function(callback) {
this.autocomplete.addListener('place_changed', function() {
var place = this.autocomplete.getPlace();
if (!place.geometry) {
window.alert("Der Ort konnte nicht gefunden werden");
return;
}
callback(place);
}.bind(this));
},
createMarker: function() {
var marker = new google.maps.Marker({
map: this.map
})
return marker;
}
}
}
GISView.vue
<template>
<div ref="map" id="map" class="google-map" style="height: 800px; position: relative; overflow: hidden;">
</div>
</template>
<script>
import GoogleMaps from '../mixins/GoogleMaps.js';
export default {
mixins: [GoogleMaps],
data() {
return {
initialLocation: '',
autocompletePlace: ''
}
},
mounted() {
this.$events.$on("MapsAPILoaded", eventData => this.initMap());
},
methods: {
initMap: function() {
this.initialLocation = this.createInitialLocation(48.184845, 11.252553);
this.mapSetup(this.$refs.map, this.initialLocation, function() {
this.initAutoCompleteListener(function(place) {
this.autocompletePlace = place;
})
}.bind(this));
}
}
}
</script>
最佳答案
您绑定(bind)了外部函数,但未绑定(bind)内部函数。尝试
this.initAutoCompleteListener(function(place) {
this.autocompletePlace = place;
}.bind(this))
关于javascript - VueJS2 访问 Child 中的 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43926037/