DEV Community

Cover image for A simple way to keep your Vue page title in sync with the router

A simple way to keep your Vue page title in sync with the router

Karolis on September 08, 2019

I have noticed in quite a few projects that developers forget to keep page title updated with the router or maybe think that they will do it tomorr...
Collapse
 
lpellis profile image
Loftie Ellis

Updating the title is definetly something a lot of spa's seems to neglect.
In your example you should probably specify immediate:true for the watch, otherwise the title wont update on the first load

watch: {
      '$route':{
        handler: (to, from) => {
          document.title = to.meta.title || 'Your Website'
        },
         immediate: true
      }
    },
Enter fullscreen mode Exit fullscreen mode

And if you start adding more metadata I would recommend looking at github.com/nuxt/vue-meta

Collapse
 
dinsmoredesign profile image
Derek D • Edited

Navigation guard inside your router makes more sense structurally IMO, but each work well:

router.beforeEach((to, from, next) => {
  document.title = to.meta.title || 'Your Website Title');
  next();
});
Enter fullscreen mode Exit fullscreen mode

;)

Collapse
 
psnehanshu profile image
Snehanshu Phukon

Another way is using router.afterEach

router.afterEach((to, from) => {
  if (to.meta && to.meta.title) {
    document.title = to.meta.title + ' | Any suffix';
  }
});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
imalexlab profile image
Alex Lab

Hello, here is a version with the composition API:

<script lang="ts">
import { defineComponent, watch } from 'vue';
import { useRoute } from 'vue-router';

export default defineComponent({
  setup() {
    const route = useRoute();

    watch(
      () => route.meta.title,
      () => {
        document.title = route.meta.title as string;
      }
    );
  },
});
</script>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pastorsi profile image
Simon Measures

I'm wondering why you have Step 2 with the title "Add $route watcher in your App.vue" but then the tutorial text instructs us to put the watcher in main.vue. Could you please clarify this.

Collapse
 
krusenas profile image
Karolis Webhook Relay

By main vue file I meant the file that contains the router view inside it. Some template generators that I used would name it App.vue :)

Collapse
 
akifobaidi profile image
AkifObaidi

Thanks so Much.

Collapse
 
alindebian profile image
alin

Thanks so much!