Skip to content

Commit

Permalink
feat(reactivity): add triggerRef API
Browse files Browse the repository at this point in the history
Also make shallowRef assignment behavior consistent with normal ref
  • Loading branch information
yyx990803 committed Apr 22, 2020
1 parent 3e60288 commit 2acf3e8
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 3 deletions.
4 changes: 2 additions & 2 deletions packages/reactivity/__tests__/ref.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
isReactive
} from '../src/index'
import { computed } from '@vue/runtime-dom'
import { shallowRef, unref, customRef } from '../src/ref'
import { shallowRef, unref, customRef, triggerRef } from '../src/ref'

describe('reactivity/ref', () => {
it('should hold a value', () => {
Expand Down Expand Up @@ -194,7 +194,7 @@ describe('reactivity/ref', () => {
expect(dummy).toBe(1) // should not trigger yet

// force trigger
sref.value = sref.value
triggerRef(sref)
expect(dummy).toBe(2)
})

Expand Down
1 change: 1 addition & 0 deletions packages/reactivity/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export {
toRef,
toRefs,
customRef,
triggerRef,
Ref,
UnwrapRef
} from './ref'
Expand Down
11 changes: 10 additions & 1 deletion packages/reactivity/src/ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ function createRef(rawValue: unknown, shallow = false) {
return value
},
set value(newVal) {
if (shallow || hasChanged(toRaw(newVal), rawValue)) {
if (hasChanged(toRaw(newVal), rawValue)) {
rawValue = newVal
value = shallow ? newVal : convert(newVal)
trigger(
Expand All @@ -70,6 +70,15 @@ function createRef(rawValue: unknown, shallow = false) {
return r
}

export function triggerRef(ref: Ref) {
trigger(
ref,
TriggerOpTypes.SET,
'value',
__DEV__ ? { newValue: ref.value } : void 0
)
}

export function unref<T>(ref: T): T extends Ref<infer V> ? V : T {
return isRef(ref) ? (ref.value as any) : ref
}
Expand Down
1 change: 1 addition & 0 deletions packages/runtime-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export {
isReadonly,
// advanced
customRef,
triggerRef,
shallowRef,
shallowReactive,
shallowReadonly,
Expand Down

0 comments on commit 2acf3e8

Please sign in to comment.