0

So I have a view that provides an Object.

setup(){
  provide('string', {foo: 'bar'})
}

On page change using vue-router, I want the loaded component to inject that String but I am getting undefined.

setup() {
  const foo = inject('string')
}

Do you have any idea of how can I accomplish this?

bporcel
  • 3
  • 2
  • Is the loaded component a child of the view? Or a different view altogether? Provide is for descendant components – Dan Feb 19 '21 at 00:39
  • @shob I see... It's not a child component, it's a different view. Is there any way to inject in different views or any alternative? – bporcel Feb 19 '21 at 18:12
  • Yes, you could provide from the app root or router view root. See [this answer](https://stackoverflow.com/a/65184375/2185093) for a couple of options or use Vuex. – Dan Feb 19 '21 at 18:35

1 Answers1

0

Following @shob instruccions I ended up building a custom hook so I can acces the info in any component. I leave it here just in case someone needs it in the future.

import { provide, inject } from 'vue';
import cartProducts from '@/resources/CartProducts.ts';

const itemsSymbol = Symbol();

const provideCartBasket = (): void => {
  const items = cartProducts;
  provide(itemsSymbol, items);
};

const useCartBasket = () => {
  const cartItems = inject(itemsSymbol);
  if (!cartItems) {
    console.log('No items available');
  }
  return cartItems;
};

export { provideCartBasket, useCartBasket };
bporcel
  • 3
  • 2