How to set nuxtjs title and meta from a middleware or plugin?

Viewed 1499

How to set NuxtJS title % meta tags from nuxt-middleware/nuxt-plugin?

currently i'm setting it from nuxt.config.js like below.

  head: () => {
    const now = Date.now()
    return {
      title: `config test : ${now}`,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: 'My custom description'
        }
      ]
    }
  },

Please note that i know i can set similarly in the page component. I don't wanna set the header function in every page instead i want a common place where i can set the header dynamically with using the router instance. which is in router middle-ware or plugin.

1 Answers

You can calculate your head info in middleware depending on which route you're in. Then you can store this data in your vuex or pass it as a prop to the page. In your page you can grab this data in asyncData hook. An example of head colculation would be:

export default function ({ store, route }) {

      const headInfoCollection = [
        { name: 'home', title: "Home" },
        { name: 'about', title: "About" }
      ]

      const headInfo = headInfo.find(c => c.name === route.name)
      
      store.dispatch('setHeadInfo', headInfo)

}
Related