Vue.js中选择城市后父组件无法调用子组件map的setCenter方法
问题分析与修复方案
核心问题
- 父组件未将选中的城市数据传递给
map子组件的city_objectprops - 父组件调用
setCenter的时机错误(仅在地图初始化时触发),未在城市切换时执行 map子组件的setCenter方法设计冗余,无需传入map实例(自身已持有this.mymap)
修复后的代码
1. 父组件修改
<template> ... <dropdown-city @currentCity="updateCity"></dropdown-city> <!-- 绑定选中的城市数据给map组件 --> <map ref="mymap" :city-object="city_object" @myMap="updateMap"></map> ... </template> <script> export default { data() { return { city_object: null, // 初始化城市数据 mapInstance: null // 保存地图实例用于判断 } }, ... methods: { updateCity(city) { this.city_object = city // 城市切换时调用map组件的定位方法 if (this.mapInstance) { this.$refs.mymap.setCenter() } }, updateMap(map) { this.mapInstance = map } } ... } </script>
2. map子组件修改
<template> <div> <div id="mymap" class="vue2leaflet-map"></div> </div> </template> <script> export default { data: function() { return { mymap: "", center_lat: 37.2756354, center_lng: -104.6563627, }; }, mounted() { var map = L.map("mymap", { fullscreenControl: !1 }).setView([this.center_lat, this.center_lng], 18); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a>' }).addTo(map); this.mymap = map; this.$emit('myMap', map); }, methods: { // 移除冗余参数,使用自身持有的地图实例 setCenter: function () { console.log("setCenter"); if (this.city_object) { // 增加空值判断避免报错 this.mymap.flyTo([this.city_object.lat, this.city_object.lng], 14, {animate: true, duration: 0.25, noMoveStart: true}); } }, }, props: { city_object: Object, }, // 可选:通过监听自动触发定位,无需父组件手动调用 watch: { city_object(newCity) { if (newCity) { this.setCenter() } } } } </script>
额外优化(可选)
如果使用watch监听city_object,父组件可简化updateCity方法,完全依赖响应式触发:
updateCity(city) { this.city_object = city }
此时城市切换时,map子组件会自动执行定位逻辑,无需手动调用子组件方法,更符合Vue响应式设计理念。
内容的提问来源于stack exchange,提问作者Hai Truong IT
相关产品推荐
相关产品推荐

