Skip to content

Commit ae44409

Browse files
committed
fix: prevent computed from being called before accessing it
Resolves: #79
1 parent 558504a commit ae44409

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

src/reactivity/ref.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,10 @@ class RefImpl<T> implements Ref<T> {
9595
}
9696

9797
export function createRef<T>(options: RefOption<T>) {
98-
return new RefImpl<T>(options);
98+
// seal the ref, this could prevent ref from being observed
99+
// It's safe to seal the ref, since we really shoulnd't extend it.
100+
// related issues: #79
101+
return Object.seal(new RefImpl<T>(options));
99102
}
100103

101104
type RefValue<T> = T extends Ref<infer V> ? V : UnwrapRef<T>;

test/apis/state.spec.js

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
const Vue = require('vue/dist/vue.common.js');
2-
const { reactive, ref, watch, set, toRefs } = require('../../src');
2+
const { reactive, ref, watch, set, toRefs, computed } = require('../../src');
33

44
describe('api/ref', () => {
55
it('should work with array', () => {
@@ -350,4 +350,19 @@ describe('unwrapping', () => {
350350
});
351351
expect(dummy).toBe(a);
352352
});
353+
354+
it('should not call the computed property until accessing it', () => {
355+
const spy = jest.fn();
356+
const state = reactive({
357+
count: 1,
358+
double: computed(() => {
359+
spy();
360+
return state.count * 2;
361+
}),
362+
});
363+
364+
expect(spy).not.toHaveBeenCalled();
365+
expect(state.double).toBe(2);
366+
expect(spy).toHaveBeenCalled();
367+
});
353368
});

0 commit comments

Comments
 (0)