报错Uncaught TypeError: Cannot read property 'activeElement' of undefined,Google Places SearchBox问题排查
解决Uncaught TypeError: Cannot read property 'activeElement' of undefined(Google Places SearchBox)
嘿,这个问题我之前也踩过坑!核心原因很明确:Google Places的SearchBox构造函数需要接收真实的DOM元素,而不是Vue的响应式数据变量。你现在把this.origin(这是和input绑定的字符串值)传进去了,它自然找不到activeElement这个DOM专属的属性。
给你两个简单的修复步骤:
- 先给input元素加个
ref属性,让Vue能精准定位到这个DOM节点:
<input placeholder="Search Box" v-model="origin" type="text" ref="searchInput">
- 在
mounted钩子里面,通过Vue的$refs获取到真实的DOM元素,再传给SearchBox:
mounted(){ // 这里取的是DOM元素,不是Vue的响应式变量 const input = this.$refs.searchInput; const searchBox = new google.maps.places.SearchBox(input); searchBox.addListener('places_changed', function() { const places = searchBox.getPlaces(); // 这里可以添加你需要的地点处理逻辑,比如打印看看结果 console.log('获取到的地点:', places); }); },
补充一句:mounted钩子执行的时候,Vue已经完成了页面DOM的挂载,所以用$refs获取DOM元素是安全的。你在index.html里引入API的操作是没问题的,不用改~
内容的提问来源于stack exchange,提问作者Bogart
相关产品推荐
相关产品推荐

