Search code examples
vue.jsvue-componentvuejs3nuxt3.js

Breadcrumbs component: passing data between page and layout


I want to pass the data from page pages/index.vue to default layout layouts/default.vue. to set the dynamic breadcrumb according to the current page with the custom breadcrumb segment.

I have tried the vue 3 provide and inject option but not working and return always injection "foo" not found.. Please share ideas to archive this thing.


Solution

  • You can use useState composable link. Which is provided by nuxt to share data across components. Or you can use a state management system like vuex or pinia

    From nuxt.com useState is,

    Nuxt provides useState composable to create a reactive and SSR-friendly shared state across components.

    You can declare any variable with useState like this inside your pages directory

    <script setup>
    const counter = useState('counter', () => Math.round(Math.random() * 1000));
    </script>
    
    <template>
      <h1>Index page</h1>
      <div>
        <button @click="counter++">Inc Counter From Index</button>
        <button @click="counter--">Dec Counter From Index</button>
      </div>
    </template>
    
    

    Then you can access that variable using useState from your layout like this

    <script setup>
    const counter = useState('counter');
    </script>
    
    <template>
      <div>
        Some default layout shared across all pages
    
        <h3>Counter value from the default layout = {{ counter }}</h3>
        <slot />
      </div>
    </template>
    
    

    Overall a minimal example are given in stackBliz here link