As shown in this similar Vue question, this is a common problem with legacy libraries that use dynamic this
context instead of arguments to supply data to callback functions.
Whenever possible, try to use arguments, some libraries promote the use of this
but also provide necessary data as arguments:
test.customEvent('changeEvent', e => {
console.log(e); // possibly an event
console.log(this); // vue instance
});
If this is not the case, self = this
hack can be used:
const self = this;
test.customEvent('changeEvent', function () {
console.log(this); // event
console.log(self); // vue instance
});
A workaround that is compatible with Vue methods that are pre-bound to Vue instance is the use of helper function that passes dynamic context as an argument:
function contextWrapper(fn) {
const self = this; // doesn't matter if used solely with Vue methods
return function (...args) {
return fn.call(self, this, ...args);
}
}
...
setSwiper() {
const test = new something;
test.customEvent('changeEvent', contextWrapper(this.handleChange));
},
handleChange(e){
console.log(e); // event
console.log(this); // vue instance
}