google-maps - 在 vue 组件内的 javascript 实例化组件上添加事件处理程序。(google.maps.DirectionsRenderer)
问题描述
我们有一个 vue 应用程序,其中包含一个使用 Google 方向 API 的 google 应用程序组件。为此,我们启动地图,并创建一个 DirectionsService 实例和一个 DirectionsRenderer 实例。我们需要在路由更改时调用一个函数。
methods: {
initMap() {
if (this.$refs.baseMap) {
this.$refs.baseMap.$mapPromise.then(map => {
this.directionsService = new google.maps.DirectionsService
this.directionsRenderer = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
})
this.directionsRenderer.addListener('directions_changed',
function() {
this.computeTotalDistance() // I need this to be a called when the direction change
}
)
})
}
},
computeTotalDistance(){
// do some code
}
上面的代码不理解“this”是什么,因为它在 addListener 函数中。我如何使它工作?
解决方案
添加一个变量引用this
应该可以工作:
const self = this
this.directionsRenderer.addListener('directions_changed',
function() {
self.computeTotalDistance() // I need this to be a called when the direction change
}
)
推荐阅读
- kubernetes - Apache kafka 的 zookeeper 和 broker 使用的建议卷方法是什么?
- android - 我如何处理芯片组中的多个芯片选择?
- javascript - 无法弄清楚这个功能是如何工作的
- javascript - 如何从浏览器 javascript 访问 thingsboard REST API?
- angular - useFactory Provider 用于模块中的分离服务实例
- selenium-webdriver - 如何在 CSS Selector 字符串中使用 Method 的参数?
- ios - UITableView Cell ( Autoscroll ) 内的多个 CollectionView 问题
- python - 如何修复 pip 未被识别为命令?
- sql - 获得每所学校男女学生的最高 GPA 分数
- sql-server - TRY CAST 可用并且 TRY CONVERT 不在 SQL Server 2012 中?