Skip to content

Setup context hook for dependency injection #1598

Closed
@AlexandreBonaventure

Description

@AlexandreBonaventure

What problem does this feature solve?

Here is a utility helper I like to use

export function useLocalModel ({ props, emit }, propName) {
  return computed({
    get () {
      return props[propName];
    },
    set (val) {
      emit(`update:${propName}`, val);
    },
  });
}

Here, the dependency injection is cumbersome / no conventions + no standard (should the argument be the first one ? the last one ?)

What does the proposed API look like?

Thinking about it, I came up with an elegant solution, that I don't think would be super difficult to implement:
Introduce a new built-in useContext composition function that would allow users to get the current setup function context (props, attrs, emit, slots).
Here it will make this composition a lot more clean and simple:

import { useContext } from 'vue'
export function useLocalModel (propName) {
  const { props, emit } = useContext()
  return computed({
    get () {
      return props[propName];
    },
    set (val) {
      emit(`update:${propName}`, val);
    },
  });
}

This is probably too simple to raise a RFCs but if there is a need, feel free to ask.
Regards.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions