vueJS router: Update page title from component data

Viewed 256

I'm running VueJS with vue router installed, the titles are currently working OK except from one detail.

In the example below all pages work OK, however if I use the /user/:user_id route to display a specific user I don't know how to show the username in the title, e.g: 'Cool Page - [USER_NAME]'.

This username is obtained in the Component from the database after the component uses the :user_id to retrieve that users data from Vuex.

How can I do this?

routes: [
  {
      path: '/',
      name: 'Home',
      component: Home,
      meta: {'title': "Cool Page",
        'metaTags': metaTags},
    },
    {
      path: '/users',
      name: 'users',
      component: Users,
      meta: {'title': "CoolPage - Users",
        metaTags: metaTags},
    },
     {
      path: '/user/:user_id',
      name: 'user',
      component: User,
      meta: {'title': "Cool Page - Some User",
        metaTags: metaTags },
...
const DEFAULT_TITLE = 'Coolpage.com';
router.afterEach((to, from) => {
    document.title = to.meta.title || DEFAULT_TITLE;
});

In my Component: I have a computed property to use the vuex getter, and a data variable for the prop, like this:

computed: {
    ...mapGetters(['allUsers','getUserById', 'getUserStoreStatus']),
    user: function () {
      var u = this.getUserById(this.user_id);
      if(u){ return u; }
      else{ return {}; }
    },
},
data(){
    return {
      user_id: this.$route.params.user_id,
    }
 }
...
1 Answers

I would simply import your store where you are getting the user info, like this:

import store from '../store';

Then you will do something like this (I haven't seen your store code so you'll have to alter this bit to fit your needs):

const DEFAULT_TITLE = 'Coolpage.com';
router.afterEach((to, from) => {
    const userInfo = store.getters['getUserInfo'];
    // This could be cleaned up a bit, but you get the point...
    document.title = to.name === 'user' ? 
        `Cool Page - ${userInfo.username}` : 
        to.meta.title || DEFAULT_TITLE;
});
Related