From 859d094bd993f4714093af17182ed73dd98659c5 Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Wed, 21 Jul 2021 18:00:17 +0200 Subject: [PATCH] feat: allow actions to be destructured --- __tests__/actions.spec.ts | 24 ++++++++++++++++++++++++ src/store.ts | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/__tests__/actions.spec.ts b/__tests__/actions.spec.ts index ecd507ab..36d7e2c7 100644 --- a/__tests__/actions.spec.ts +++ b/__tests__/actions.spec.ts @@ -25,6 +25,11 @@ describe('Actions', () => { async getNonA() { return this.nonA }, + simple() { + this.toggle() + return 'simple' + }, + toggle() { return (this.a = !this.a) }, @@ -211,4 +216,23 @@ describe('Actions', () => { }) await expect(store.getNonA()).resolves.toBe('hello') }) + + it('can destructure actions', () => { + const store = useStore() + const { simple } = store + expect(simple()).toBe('simple') + // works with the wrong this + expect({ simple }.simple()).toBe('simple') + // special this check + expect({ $id: 'o', simple }.simple()).toBe('simple') + // override the function like devtools do + expect( + { + $id: store.$id, + simple, + // otherwise it would faial + toggle() {}, + }.simple() + ).toBe('simple') + }) }) diff --git a/src/store.ts b/src/store.ts index b8ca5857..87dc9ea4 100644 --- a/src/store.ts +++ b/src/store.ts @@ -310,7 +310,7 @@ function createSetupStore< let ret: any try { - ret = action.apply(this || store, args) + ret = action.apply(this && this.$id === $id ? this : store, args) // handle sync errors } catch (error) { if (onErrorCallback(error) !== false) { -- 2.47.2