How to properly use nested components in nuxt.js

3.2k Views Asked by At

Good day! Lord please tell me how to use nested components in nuxt js?

// ~/components/general/Page.vue

<template lang="pug">
  div(id="page" class="align-center")
</template>

// ~/components/general/Header.vue

<template lang="pug">
  header
    div(class="align-center align-middle")
      img(src="~/assets/general/header/logo.png")
</template>

// pages/index.vue

<template lang="pug">
 div
  page
   test
</template>

<script>
 import page from '~/components/general/Page.vue'
 import test from '~/components/general/Header.vue'

 export default {
  components: {
    page,
    test
  }
}
</script>

And accordingly this design does not work. What it is necessary to make that it earned? I will be grateful for an example

I tried to use the slot in the parent component, but I still could not get it to work

// ~/components/general/Page.vue

<template lang="pug">
  div(id="page" class="align-center")
   slot
</template>
1

There are 1 best solutions below

0
On

Why don't you include the Head component into your Page component, like this:

// ~/components/general/Page.vue

<template lang="pug">
  div(id="page" class="align-center")
    my-header
</template>
<script>
  import MyHeader from '~/components/general/Header.vue'
  export default {
    components: {
      MyHeader
    }
  }
</script>

// ~/components/general/Header.vue

<template lang="pug">
  header
    div(class="align-center align-middle")
      img(src="~/assets/general/header/logo.png")
</template>

// pages/index.vue

<template lang="pug">
 div
  page
</template>

<script>
 import page from '~/components/general/Page.vue'

 export default {
  components: {
    page,
  }
}
</script>

Also I would like to suggest that you put these components into your layout files. It would make much more sense if you'd do it this way:

// ~/components/general/Header.vue

<template lang="pug">
  header
    div(class="align-center align-middle")
      img(src="~/assets/general/header/logo.png")
</template>

// layouts/default.vue

<template lang="pug">
  div(id="page" class="align-center")
    my-header
    nuxt
</template>

<script>
  import MyHeader from '~/components/general/Header.vue'
  export default {
    components: {
      MyHeader
    }
  }
</script>

// And then the <nuxt></nuxt> will be replaced by whatever you put inside
// your pages files

// pages/index.vue

<template lang="pug">
 div
  h1 My Page
</template>

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