Skip to content

Commit 2acf3e8

Browse files
committed
feat(reactivity): add triggerRef API
Also make shallowRef assignment behavior consistent with normal ref
1 parent 3e60288 commit 2acf3e8

File tree

4 files changed

+14
-3
lines changed

4 files changed

+14
-3
lines changed

packages/reactivity/__tests__/ref.spec.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
isReactive
1010
} from '../src/index'
1111
import { computed } from '@vue/runtime-dom'
12-
import { shallowRef, unref, customRef } from '../src/ref'
12+
import { shallowRef, unref, customRef, triggerRef } from '../src/ref'
1313

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

196196
// force trigger
197-
sref.value = sref.value
197+
triggerRef(sref)
198198
expect(dummy).toBe(2)
199199
})
200200

packages/reactivity/src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ export {
66
toRef,
77
toRefs,
88
customRef,
9+
triggerRef,
910
Ref,
1011
UnwrapRef
1112
} from './ref'

packages/reactivity/src/ref.ts

+10-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ function createRef(rawValue: unknown, shallow = false) {
5555
return value
5656
},
5757
set value(newVal) {
58-
if (shallow || hasChanged(toRaw(newVal), rawValue)) {
58+
if (hasChanged(toRaw(newVal), rawValue)) {
5959
rawValue = newVal
6060
value = shallow ? newVal : convert(newVal)
6161
trigger(
@@ -70,6 +70,15 @@ function createRef(rawValue: unknown, shallow = false) {
7070
return r
7171
}
7272

73+
export function triggerRef(ref: Ref) {
74+
trigger(
75+
ref,
76+
TriggerOpTypes.SET,
77+
'value',
78+
__DEV__ ? { newValue: ref.value } : void 0
79+
)
80+
}
81+
7382
export function unref<T>(ref: T): T extends Ref<infer V> ? V : T {
7483
return isRef(ref) ? (ref.value as any) : ref
7584
}

packages/runtime-core/src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export {
1616
isReadonly,
1717
// advanced
1818
customRef,
19+
triggerRef,
1920
shallowRef,
2021
shallowReactive,
2122
shallowReadonly,

0 commit comments

Comments
 (0)