Skip to content

Conversation

stafyniaksacha
Copy link

@stafyniaksacha stafyniaksacha commented Oct 10, 2023

This introduces toShallowRef which act like toRef but to produce shallowRef instead of ref

// convert ref/reactive to shallowRef
toShallowRef(ref('Hello World')) // ShallowRef<string>
toShallowRef(reactive({ foo: 1 })) // ShallowRef<{ foo: number }>

// convert object keys like toRef
toShallowRef({ nested: { foo: 1 }}, 'nested') // ShallowRef<{ foo: number }>

// accept computed getter
toShallowRef(() => 'Hello World') // Readonly<ShallowRef<string>>

// act like shallowRef on raw values
toShallowRef('Hello World') // ShallowRef<string>

// preserve shallowRef
const shallow = shallowRef('Hello World')
toShallowRef(shallow) === shallow // true

@stafyniaksacha stafyniaksacha changed the title feat(reactivity): add toShallowRef feat(reactivity): add toShallowRef Oct 10, 2023
@skirtles-code
Copy link
Contributor

Maybe worth comparing to #8530.

@stafyniaksacha
Copy link
Author

Maybe worth comparing to #8530.

I've changed the behavior when having ref/reactive in input, now it converts to shallowRef. I also implemented toShallowRef({ nested: { foo: 1 }}, 'nested') to match toRef.

Furthermore, I also took care about isShallow(toShallowRef(..)) via __v_isShallow internal flag

Note: I need to clean up tests

@pikax
Copy link
Member

pikax commented Oct 13, 2023

New API's should have a RFC attached

@Alfred-Skyblue
Copy link
Member

I believe that when we use toShallowRef on a reactive object like toShallowRef({ nested: { foo: 1 }}, 'nested'), even when using toRaw, it can still affect the original data of the reactive object. When we use shallowRef for deep updates, the original data of the reactive object also gets updated, making it difficult to trace the source of data updates.

vuejs/rfcs#506 (comment)

@undergroundwires
Copy link

This implementation lacks following signatures:

export declare function toRef<T extends object, K extends keyof T>(object: T, key: K): ToRef<T[K]>;
export declare function toRef<T extends object, K extends keyof T>(object: T, key: K, defaultValue: T[K]): ToRef<Exclude<T[K], undefined>>;

Added on comment on RFC, and mentioning here as well, this API should allow all usages of toRef including multiple parameters.

Ability to do toShallowRef(props, 'propName') communicates the intent and expected behavior much better, see vuejs/rfcs#506 (comment).

@edison1105 edison1105 added the duplicate This issue or pull request already exists label Aug 28, 2024
@edison1105
Copy link
Member

duplicate of #8530

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

duplicate This issue or pull request already exists scope: reactivity ✨ feature request New feature or request version: minor

Projects

Status: Rejected

Development

Successfully merging this pull request may close these issues.

7 participants