NuxtJS(Vue.js) v-if内Google Maps及Autocomplete切换后显示异常问题
问题核心原因
- 模板中使用
v-if控制地图容器的显隐时,Vue会在instore为false的状态下直接销毁容器对应的DOM节点,只有instore切回true时才会重新创建全新的DOM节点。 toggle方法的执行顺序存在逻辑问题:修改instore响应式状态后,立刻同步访问this.$refs.map和this.$refs.citySearch。但Vue的DOM更新是异步批量执行的,此时新的DOM还未渲染完成,两个ref对应的内容都是undefined,传给Google Maps的初始化方法时,就会抛出“期望传入Element类型但拿到undefined”的错误。- 原实现没有做实例缓存,每次方法调用都直接新建Google Maps、Autocomplete实例,重复绑定DOM会造成页面渲染空白、内存泄漏。
修复方案
1. 调整初始化逻辑的执行时机
不要在修改响应式状态后立刻同步访问DOM引用,使用Vue内置的$nextTick方法,等Vue完成DOM更新、真实生成容器节点后,再执行地图初始化逻辑。
2. 缓存实例避免重复创建
将已经初始化好的地图、地址自动补全实例存储在组件内部,不需要每次切换显隐都重新创建实例,减少资源浪费和渲染异常。
3. 可选优化
如果只是简单切换显隐状态、不需要频繁销毁DOM,可以将v-if替换为v-show——v-show仅通过CSS的display: none控制显隐,不会销毁DOM节点,DOM引用不会丢失。仍建议做好实例缓存,不要完全依赖DOM常驻的特性。
核心代码调整示例
main.vue 修复后逻辑
<template> <div> Hi {{ username }} <input v-model="businessName" type="text" placeholder="Business Name" /><br /><br /> In-store Address:<br /> <input type="checkbox" @change="toggle()" />Not applicable<br /><br /> <div v-if="instore"> <input type="text" ref="citySearch" @changed="changed" /><br /><br /> <div style="height:800px;width:800px" ref="map"></div> <br /><br /> </div> <button type="button" @click="updateMap">Submit</button><br /> </div> </template> <script> export default { data() { return { businessName: "", businessAddress: "", instore: true, // 缓存已初始化的实例 mapInstance: null, autocompleteInstance: null }; }, mounted() { // 首次组件挂载完成后,等DOM渲染完毕再初始化地图相关能力 this.$nextTick(() => { this.initMapFeatures(); }); }, computed: { username() { return this.$store.state.username; } }, methods: { // 抽离公共初始化逻辑,复用已有实例 initMapFeatures() { // 先校验DOM节点是否真实存在,不存在直接跳过初始化 if (!this.$refs.citySearch || !this.$refs.map) return; // 实例不存在才新建,已存在直接复用 if (!this.autocompleteInstance) { this.autocompleteInstance = this.$maps.makeAutoComplete(this.$refs.citySearch); } if (!this.mapInstance) { this.mapInstance = this.$maps.showMap(this.$refs.map, -33.86, 151.2); } }, toggle() { this.instore = !this.instore; // 等DOM更新完成后再执行初始化 this.$nextTick(() => { this.initMapFeatures(); }); }, submit(e) { if (!this.businessName || !this.businessAddress) { return; } this.$store.commit("add_business", this.name, this.address); }, updateMap() { // 已有实例时直接更新地图中心,不要重新新建实例 if (this.mapInstance) { this.mapInstance.setCenter(new window.google.maps.LatLng(this.lat, this.lng)); } else { this.$maps.showMap(this.$refs.map, this.lat, this.lng); } }, changed(event) { const place = event.detail; // 已有实例时直接更新地图位置与缩放级别 if (this.mapInstance) { const position = new window.google.maps.LatLng( place.geometry.location.lat(), place.geometry.location.lng() ); this.mapInstance.setCenter(position); this.mapInstance.setZoom(18); } else { this.$maps.showMap( this.$refs.map, place.geometry.location.lat(), place.geometry.location.lng() ); } } } }; </script>
maps.client.js 适配调整
原有showMap和makeAutoComplete方法需要将创建好的实例返回,方便外部组件缓存:
function makeAutoComplete(input) { if (!isLoaded) { waiting.push({ fn: makeAutoComplete, arguments }); return; } const autoComplete = new window.google.maps.places.Autocomplete(input); autoComplete.addListener("place_changed", () => { const place = autoComplete.getPlace(); input.dispatchEvent(new CustomEvent("changed", { detail: place })); }); // 返回创建好的自动补全实例 return autoComplete; } function showMap(canvas, lat, lng) { if (!isLoaded) { waiting.push({ fn: showMap, arguments }); return; } const mapOptions = { zoom: 18, center: new window.google.maps.LatLng(lat, lng), disableDefaultUI: true, zoomControl: true }; const map = new window.google.maps.Map(canvas, mapOptions); const position = new window.google.maps.LatLng(lat, lng); const marker = new window.google.maps.Marker({ position }); marker.setMap(map); // 返回创建好的地图实例 return map; }
额外注意:如果坚持使用
v-if的销毁重建逻辑,DOM重新生成后,需要将已缓存的地图实例通过mapInstance.setDiv(newDomElement)方法重新绑定到新的DOM节点上,不需要完全重新创建实例,既可以保留之前的地图状态,也能避免渲染异常。
内容的提问来源于stack exchange,提问作者Matty
相关产品推荐
相关产品推荐

