Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using nuxt, how do I put the route name in the page title?

I want to set the page title to a different value for each page.

In regular Vue.js, I have done the following:

import router from './router'
import { store } from './store/store';

router.beforeEach((to, from, next) => {
    store.mutations.setRoute(to);
    document.title = store.getters.pageTitle;
    next();
}

How would I get that effect in nuxt?

That is, on both initial page load and when changing pages, I want the browser tab's title to change. For instance, from "My App - About" to "My App - Profile".

like image 527
Paulie Avatar asked Jan 16 '18 16:01

Paulie


2 Answers

from nuxt docs, in each pages component you can define the head function that returns the title of page i.e.

head() {
    return {
      title: "About page"
    };
  }
like image 184
Lahori Avatar answered Oct 24 '22 21:10

Lahori


I found a way to do this, but I don't know if it is the "right" way. I use the mounted() function in default.vue for the initial page load and the transition property in nuxt.config.js for each page change. So, in default.vue:

...mapGetters(['appTitle']),
...mapMutations(['setRoute']),
mounted() {
    this.setRoute(this.$route.name);
    document.title = this.appTitle();
}

And in nuxt.config.js:

transition: {
    name: 'page',
    mode: 'out-in',
    beforeEnter (el) {
        this.$store.commit("setRoute", this.$route.name);
        document.title = this.$store.getters.appTitle;
    }
},
like image 37
Paulie Avatar answered Oct 24 '22 21:10

Paulie