Skip to content

Commit 2f3ec44

Browse files
committed
feat: add unref API to match API with vue3
1 parent bacf216 commit 2f3ec44

File tree

4 files changed

+13
-3
lines changed

4 files changed

+13
-3
lines changed

src/apis/state.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
export { reactive, ref, Ref, isRef, toRefs, set } from '../reactivity';
1+
export { reactive, ref, Ref, isRef, toRefs, set, unref } from '../reactivity';

src/reactivity/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
export { reactive, isReactive, nonReactive } from './reactive';
2-
export { ref, isRef, Ref, createRef, UnwrapRef, toRefs } from './ref';
2+
export { ref, isRef, Ref, createRef, UnwrapRef, toRefs, unref } from './ref';
33
export { set } from './set';

src/reactivity/ref.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,10 @@ export function isRef<T>(value: any): value is Ref<T> {
132132
return value instanceof RefImpl;
133133
}
134134

135+
export function unref<T>(ref: T): T extends Ref<infer V> ? V : T {
136+
return isRef(ref) ? (ref.value as any) : ref;
137+
}
138+
135139
// prettier-ignore
136140
type Refs<Data> = {
137141
[K in keyof Data]: Data[K] extends Ref<infer V>

test/apis/state.spec.js

Lines changed: 7 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, computed } = require('../../src');
2+
const { reactive, ref, watch, set, toRefs, computed, unref } = require('../../src');
33

44
describe('api/ref', () => {
55
it('should work with array', () => {
@@ -330,6 +330,12 @@ describe('unwrapping', () => {
330330
expect(state.list[0].value).toBe(0);
331331
});
332332

333+
it('should unrwap ref', () => {
334+
expect(unref(0)).toBe(0);
335+
expect(unref(ref(0))).toBe(0);
336+
expect(unref({ value: 1 })).toStrictEqual({ value: 1 });
337+
});
338+
333339
it('should now unwrap plain object when using set at Array', () => {
334340
const state = reactive({
335341
list: [],

0 commit comments

Comments
 (0)