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

krusenas

Karolis

Posted on September 8, 2019

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

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 tomorrow as it is such a small feature :). It always makes sense to keep the title synchronized with the contents for several reasons:

  • helps users with more than one tab
  • important for website analytics

I will show you how to do it with the standard vue-router.

Step 1: Declare route meta in your router config

First things first, let's add some additional metadata to our standard routes:

  routes: [
    {
      path: '/',
      name: 'home',
      component: HomePage,
      meta: {
        auth: true,
        title: 'Dashboard'
      }
    }, {
      path: '/login',
      name: 'login',
      component: LoginPage,
      meta: {
        auth: false,
        title: 'Login'
      }
    }, {
      path: '/buckets',
      name: 'buckets',
      component: BucketsPage,
      meta: { auth: true, title: 'Buckets' }
Enter fullscreen mode Exit fullscreen mode

More docs on the router package can be found in the official vue router website.

Step 2: Add $route watcher in your App.vue

Go to your Vue main .vue file (it should have a <router-view></router-view> component) and add a watcher:

    watch: {
      '$route' (to, from) {
        document.title = to.meta.title || 'Your Website'
      }
    },

Enter fullscreen mode Exit fullscreen mode

This will set a title as your page title (if you specified a meta field for that route). I have tried to achieve the same with router navigation guards but $route watcher seemed like the simplest solution.

Looks easy, right? :) Feel free to experiment and define more fields in the router meta like page description and anything else you want to be set for that page. Then modify the watcher to also use them.

Hope this helps!

šŸ’– šŸ’Ŗ šŸ™… šŸš©
krusenas
Karolis

Posted on September 8, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related