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' }
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'
}
},
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!
Top comments (8)
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
And if you start adding more metadata I would recommend looking at github.com/nuxt/vue-meta
Navigation guard inside your router makes more sense structurally IMO, but each work well:
;)
Another way is using
router.afterEach
Hello, here is a version with the composition API:
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.
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 :)
Thanks so Much.
Thanks so much!