Home > Software engineering >  Nuxt3 Pass data from app.vue to a layout or page
Nuxt3 Pass data from app.vue to a layout or page

Time:10-21

In app.vue I have

<template>
  <Html :>
    <Body>
      <NuxtLayout>
        <NuxtPage/>
      </NuxtLayout>
    </Body>
  </Html>
</template>

<script lang="ts" setup>
import { AppSetup } from './utils/app';
import { ITheme } from './utils/theme';
AppSetup()
const theme = useState<ITheme>('theme.current')
</script>

This is what I see in the Vue devtools enter image description here

And Even that the <Html :> is filled with the theme value. If I try to:

<template>
  <Html :>
    <Body>
      <NuxtLayout :theme="theme">
        <NuxtPage :theme="theme" />
      </NuxtLayout>
    </Body>
  </Html>
</template>

<script lang="ts" setup>
import { AppSetup } from './utils/app';
import { ITheme } from './utils/theme';
AppSetup()
const theme = useState<ITheme>('theme.current')
</script>

Then the theme property is not visible from the layouts/default.vue (there's only that one) or the pages/index.vue

How can I access to that prop? If not, what's the easier way? I tried in pages/index.vue to add the same code

<script lang="ts" setup>
import { AppSetup } from '../utils/app';
import { ITheme } from '../utils/theme';
AppSetup()
const theme = useState<ITheme>('theme.current')
</script>

And this works but feels like kinda repetitive (and this doesn't work in the layouts/default.vue

This is my layouts/default.vue

<template>
  <div>
    <Header />
    <slot />
    <Footer />
  </div>
</template>

<script>
export default {
  layout: 'default'
}
</script>

And this is what I see in the devtools (the value exist) ![enter image description here

And this is my pages/index.vue

<template>
  <main>
    <h1>Welcome to <span >Nuxt3</span> for {{ brand }}</h1>
  </main>
</template>

And this is what I see in the devtools (the value exists) enter image description here

CodePudding user response:

Looking at your devtools, the props are properly passed down, you need to received them now.
For that, you could use the following in your index.vue file

<script setup>
const props = defineProps({
  theme: String
})
</script>

More details available here: https://vuejs.org/api/sfc-script-setup.html#defineprops-defineemits

  • Related