知识点:
在 JavaScript 中,事件回调函数内的 this 默认指向触发事件的 DOM 元素(或高德地图对象),而不是你的 Vue/Class 实例上下文,因此无法直接访问 this.handleLocationSelect。
解决方案:
方法 1:使用箭头函数保留外层 this
this.circle.on('click', (e) => { // 改用箭头函数const lnglat = e.lnglat;this.handleMySelect(lnglat); // 此时 this 指向外层实例
});
方法 2:通过变量保存外层 this 引用
const self = this; // 保存外层 this 的引用
this.circle.on('click', function(e) {const lnglat = e.lnglat;self.handleMySelect(lnglat); // 通过 self 访问实例方法
});
方法 3:显式绑定 this 到回调函数
this.circle.on('click', function(e) {const lnglat = e.lnglat;this.handleMySelect(lnglat);
}.bind(this)); // 使用 bind 强制绑定 this
关键解释:
箭头函数特性
箭头函数没有自己的 this,它会继承外层作用域的 this,因此能直接访问 Vue/Class 实例的 handleLocationSelect 方法。
作用域保存技巧
通过 const self = this 将外层 this 保存到变量中,闭包函数内通过 self 间接访问实例方法。
显式绑定
使用 bind(this) 强制将回调函数的 this 指向外层实例。