0

I'm working with Vue 3's Composition API, and I’m trying to provide a ref that is part of a reactive object. However, when I inject it in a child component, I get the raw value, not the reactive ref.

Here’s a simplified version of what I'm doing:

Parent component:

const position = ref("right");

const imageSetup = reactive({
  position
});

provide('position', imageSetup.position);

Child component:

const position = inject('position');

When I access position in the child, it’s just a plain string ("right") instead of a ref. I lose reactivity. If I provide(position) directly without wrapping it in a reactive object, the child receives a reactive ref and everything works fine. But I want to avoid declaring each state separately and instead use a single reactive object. I’d like to be able to structure my shared state as a single reactive object and still be able to inject individual refs from it without losing reactivity.

Is there a way to keep the reactive structure and preserve the reactivity of injected refs?

1 Answer 1

0

inject injects the exact value that was provided through provide. imageSetup.position is not a ref. position is unwrapped by reactive, resulting in typeof imageSetup.position === 'string'.

It should be:

provide('position', position)

A ref can be defined the opposite way by deriving it from reactive object:

const imageSetup = reactive({ position: "right" });
const position = toRef(imageSetup, "position");

provide('position', position);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.