0

I discovered that this is working without a problem:

Store.ts

 function setParentRoute(route: Route | undefined) {
    onBeforeMount(() => {
      parentRoute.value = route;
    });

    onBeforeUnmount(() => {
      clearParentRoute();
    });
  }

  function clearParentRoute() {
      parentRoute.value = undefined;
  }

If I call the setParentRoute function from within a component, the value for parentRoute is only set before mount, and its removed as the component is destroyed.

This saves me a lot of repetitive code and essentially functions like a mixin back in Vue 2. Is there a downside to using it like this? Or maybe even a better approach?

2
  • And why do you keep it in the store? And what goal are you pursuing?
    – imhvost
    Commented Jul 4 at 21:00
  • "Better approach" for what? This looks like XY problem and yes, doing this in an action seems fishy. Pinia stores aren't guaranteed to exist inside components, and setParentRoute isn't guarateed to be executed where it will make sense. If you want to sync a store with a router, you can do this in router's hook or access router's route directly in the store Commented Jul 5 at 9:01

0

Browse other questions tagged or ask your own question.