diff --git a/packages/pinia/__tests__/storeToRefs.spec.ts b/packages/pinia/__tests__/storeToRefs.spec.ts index d1110e8c13..17b4a3540e 100644 --- a/packages/pinia/__tests__/storeToRefs.spec.ts +++ b/packages/pinia/__tests__/storeToRefs.spec.ts @@ -1,4 +1,4 @@ -import { describe, beforeEach, it, expect } from 'vitest' +import { describe, beforeEach, it, expect, vi } from 'vitest' import { computed, reactive, ref, ToRefs } from 'vue' import { createPinia, defineStore, setActivePinia, storeToRefs } from '../src' import { set } from 'vue-demi' @@ -190,6 +190,19 @@ describe('storeToRefs', () => { expect(double.value).toEqual(1) }) + it('does not trigger getters', () => { + const n = ref(0) + const spy = vi.fn(() => n.value * 2) + const store = defineStore('a', () => { + const double = computed(spy) + return { n, double } + })() + + expect(spy).toHaveBeenCalledTimes(0) + storeToRefs(store) + expect(spy).toHaveBeenCalledTimes(0) + }) + tds(() => { const store1 = defineStore('a', () => { const n = ref(0) diff --git a/packages/pinia/src/storeToRefs.ts b/packages/pinia/src/storeToRefs.ts index 3a1cec09f5..3278b0c698 100644 --- a/packages/pinia/src/storeToRefs.ts +++ b/packages/pinia/src/storeToRefs.ts @@ -1,4 +1,5 @@ import { + computed, ComputedRef, isReactive, isRef, @@ -99,7 +100,19 @@ export function storeToRefs( const refs = {} as StoreToRefs for (const key in rawStore) { const value = rawStore[key] - if (isRef(value) || isReactive(value)) { + // There is no native method to check for a computed + // https://github.com/vuejs/core/pull/4165 + if (value.effect) { + // @ts-expect-error: too hard to type correctly + refs[key] = + // ... + computed({ + get: () => store[key], + set(value) { + store[key] = value + }, + }) + } else if (isRef(value) || isReactive(value)) { // @ts-expect-error: the key is state or getter refs[key] = // ---