Skip to content

toRefWithDeepPath | Add an utility to create a read/write ref from an object and a path #5086

@Danilouli

Description

@Danilouli

Clear and concise description of the problem

When you declare reactive objects or object refs, sometimes you want to have an isolated read/write ref to a sub path of this object.

I have already a branch with an implementation of the solution suggested below :
https://github.com/Danilouli/vueuse/tree/feat/toRefWithDeepPath

And the sub-folders with change are here :

https://github.com/Danilouli/vueuse/tree/feat/toRefWithDeepPath/packages/shared/toRefWithDeepPath
https://github.com/Danilouli/vueuse/tree/feat/toRefWithDeepPath/packages/shared/toRef

This util is quite is quite useful and used a lot in my day-to-day work (a sizeable project for an important French company) and side-projects. Any recommandation for better implementation are very welcome.

Suggested solution

The solution is a function (I called it toRefWithDeepPath but another name is possible, open to discussion), to do this with good typing.

An example would be the following:

import { toRefWithDeepPath } from '@vueuse/core'

const obj = ref({ a: { b: { c: 1 } } })
const c = toRefWithDeepPath(obj, ['a', 'b', 'c'])

console.log(c.value) // 1

c.value = 2

console.log(obj.value.a.b.c) // 2
console.log(c.value) // 2

Alternative

No response

Additional context

We could also extend the overload of toRef to manage this case, like this :

import { toRef } from '@vueuse/core'

const obj = ref({ a: { b: { c: 1 } } })
const c = toRef(obj, ['a', 'b', 'c']) // The overload comes from the array in second argument

console.log(c.value) // 1

c.value = 2

console.log(obj.value.a.b.c) // 2
console.log(c.value) // 2

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions