Nuxt.js after page refresh meta are filled from config instead of head method

912 Views Asked by At

I had problem with meta in nuxt.js app. I want to fill dynamic meta tags in one detail page

--pages
----event
-----_id.vue

When I navigate on web site via link all work great. But if I just refresh page, meta tags use value from nuxt.config.js. For instance I got 'SiteTitle Nuxt.config.js' instead of 'SiteTitle - Some event title'.

Nuxt version 2.15.3

nuxt.config.js

export default {
  head: {
    titleTemplate: '%s - SiteTitle',
    title: 'SiteTitle Nuxt.config.js',
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      {charset: 'utf-8'},
      {name: 'viewport', content: 'width=device-width, initial-scale=1'},
      {hid: 'description', name: 'description', content: ''}
    ],
    link: [
      {rel: 'icon', type: 'image/x-icon', href: '/favicon.ico'}
    ]
  }
  components: true,
  buildModules: [
    '@nuxt/typescript-build',
    '@nuxtjs/vuetify',
  ],
  modules: [`enter code here`
    '@nuxtjs/axios'
  ],

  vuetify: {
    customVariables: ['~/assets/variables.scss'],
  },
  axios: {
    baseURL: 'https://api.someurl.com',
  }
}

And _id.vue file

<template>
  <v-card class="mt-6 mb-5" outlined>
    <v-card-title>{{ model.title }}</v-card-title>
  </v-card>
</template>

<script lang="ts">
import {Component, Vue} from "nuxt-property-decorator"
import {EventModel} from "~/api/models/EventModel";
import EventApi from "~/api/EventApi";

@Component({
  async asyncData({params, $axios}) {
    const  eventApi = new EventApi($axios)
    const model = await eventApi.get(parseInt(params.id))
    return { model: model };
  },

  head(this: EventPage): object {
    return {
      title: "SiteTitle - " + this.model.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content:  this.model.shortDescription
        }
      ]
    }
  },
})
export default class EventPage extends Vue {

  model = {} as EventModel

  async fetch() {

  }
}
</script>

I tried to call api in fetch, in this case meta values always have valid value when I refresh page, but Facebook Sharing Debugger get meta from nuxt.config.js in this case, and this solution is not suitable

Thanks for your help

1

There are 1 best solutions below

0
On

You can do one thing

Create one plugin in that you can use this on router.beforeEach like this:

    app.router.beforeEach(async(to, _, next) => {
       document.title = to.meta.pageTitle ? ('Specify title - ' + ${to.meta.pageTitle}) :'Default Title';
    })

In your router file you can do something like this:

    {
        path: '/path',
        name: 'Name',
        component: Component,
        meta: {
          pageTitle: 'Change Password'
        }
    }