skip to Main Content

I’m havin a parent component, let’s say “1”, it has 2 child components, “2” and “3”, each one of this components has one child component, “4” for “2” and “5” for “3”. So the question is how to pass state from the child component “5” to last component “4” ? Probably should I use composables approach? Could you show me an example?

2

Answers


  1. You don’t need to use Pinia, you can create a "store" as simply as this:

    // on a new storeName.js file
    import { ref } from 'vue'
    export const myStore = ref('')
    

    and then import myStore on whichever component might need it, either to update it (e.g. on your component 5) or just to check its value (e.g. on your component 4). Once you change the value of myStore anywhere, it will be updated on every component. That’s it!

    Login or Signup to reply.
  2. If your components are used only together there’s a standard way to provide data for a component hierarchy:

    https://vuejs.org/guide/components/provide-inject

    Also it’s more flexible than using a store or a shared module variable (suggested by Nobsyde) since you can swap the top most component with another with the same provides and your descendant will work with them too. Your components should only agree with what provides they will work together.

    You can set default values for injected provides so your components could work outside the hierarchy or with some changed provides’ list. So your components could be context sensitive.

    Another way to share data between sibling components is scoped slots:
    How to use data from one component in another component vuejs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search