1

In my nuxt app I have a header. Based on the page that I'm in, I need to change the items of header. These items are anchor links to different parts of the page. I don't want to add header to each page seperately. I want to put header in the default layout. How can I implement it?

Shadi Farzankia
  • 639
  • 8
  • 21
  • you can use `$route.params` to detect the page you are in, and based on that show the desired link in header. take a look at this: https://stackoverflow.com/questions/44748575/how-to-get-current-route-name-in-nuxt-js – Ahmad Mobaraki Jan 27 '20 at 05:35
  • Suppose I have 7 pages in nuxt. I need headers specific for each of them and headers contain anchor links to different parts of that page. In your proposed method, the header will grow too big. – Shadi Farzankia Jan 27 '20 at 19:41
  • you can put all anchor links and titles grouped by page name in store and get the active group based on $route, them display them in your header with a v-for – Ahmad Mobaraki Jan 27 '20 at 21:10

1 Answers1

1

I would use router.js module with nested routes:

// router.js
import Vue from 'vue'
import Router from 'vue-router'

import MyFirstPage from '~/components/my-first-page'
import MySecondPage from '~/components/my-second-page'
import MyThirdPage from '~/components/my-third-page'

import MyHeaderA from '~/components/my-header-a'
import MyHeaderB from '~/components/my-header-b'

Vue.use(Router)

export function createRouter() {
  return new Router({
    mode: 'history',
    routes: [
      {
        path: '/',
        components: {
          header: MyHeaderA,
          content: MyFirstPage,
        } 
      },
      {
        path: '/b',
        components: {
          header: MyHeaderB,
          content: MySecondPage,
        } 
      },
      {
        path: '/c',
        components: {
          header: MyHeaderA,
          content: MyThirdPage,
        } 
      },
    ]
  })
}
// layout/default.vue
<template>
  <div>
    <nuxt name="header
    <nuxt name="content"></nuxt>
  </div>
</template>

I think this allow more control about routes and components in pages than the default nuxt router.

exebetche
  • 26
  • 1
  • 5