Skip to content

Commit 5b269f7

Browse files
pikaxCarlos Rodrigues
andauthored
fix: binding context vm when using function without parentheses (#148)
* fix: binding context vm when using function without parentesis #fixes 144 * improve test descriptions Co-authored-by: Carlos Rodrigues <[email protected]>
1 parent 70452af commit 5b269f7

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/setup.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,10 @@ export function mixin(Vue: VueConstructor) {
193193
if (isReactive(bindingValue)) {
194194
bindingValue = ref(bindingValue);
195195
} else {
196+
// bind function to the vm, this will make `this` = vm
197+
if (isFunction(bindingValue)){
198+
bindingValue = bindingValue.bind(vm);
199+
}
196200
// a non-reactive should not don't get reactivity
197201
bindingValue = ref(markRaw(bindingValue));
198202
}

test/setup.spec.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,4 +381,46 @@ describe('setup', () => {
381381
})
382382
.then(done);
383383
});
384+
385+
describe('Methods', () => {
386+
it('binds methods when calling with parenthesis', async ()=>{
387+
let context = null;
388+
const contextFunction = jest.fn(function (){
389+
context = this
390+
});
391+
392+
const vm = new Vue({
393+
template: '<div><button @click="contextFunction()"/></div>',
394+
setup() {
395+
return {
396+
contextFunction
397+
}
398+
}
399+
}).$mount();
400+
401+
await vm.$el.querySelector('button').click();
402+
expect(contextFunction).toBeCalled();
403+
expect(context).toBe(vm);
404+
});
405+
406+
it('binds methods when calling without parenthesis', async () => {
407+
let context = null;
408+
const contextFunction = jest.fn(function (){
409+
context = this
410+
});
411+
412+
const vm = new Vue({
413+
template: '<div><button @click="contextFunction"/></div>',
414+
setup() {
415+
return {
416+
contextFunction
417+
}
418+
}
419+
}).$mount();
420+
421+
await vm.$el.querySelector('button').click();
422+
expect(contextFunction).toBeCalled();
423+
expect(context).toBe(vm);
424+
});
425+
})
384426
});

0 commit comments

Comments
 (0)