vue.js get route name in App.vue

18,254

You can use the router's beforeEach() helper.

Example:

routes.js

import Foo from '@/components/Foo'

export default new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Foo',
      component: Foo,
      meta: {
        title: 'Foo'
      }
    }
  ]
})

In app.js or main.js or whatever your main Javascript file is. Placing the code in one of the aforementioned JS file will allow all pages to update the title accordingly and is a much cleaner way to handle the titles.

import router from '@/routes'

// your other codes here

router.beforeEach((to, from, next) => {
  document.title = `My website - ${to.meta.title}`
  next()
})
Share:
18,254
Murasaki Aikon
Author by

Murasaki Aikon

Updated on July 24, 2022

Comments

  • Murasaki Aikon
    Murasaki Aikon almost 2 years

    I used vue-cli with webpack to build up the vue project. Then I installed vue-meta-info to set up the seo.

    I want to set up the Page title with the templates and the route name. However , I cannot get the variable in router.

    rotuer/index.js

    import Vue from 'vue';
    import Router from 'vue-router';
    import HelloWorld from '@/components/HelloWorld';
    
    Vue.use(Router);
    
    export default new Router({
          mode: 'history',
          routes: [
        {
          path: '/',
          name: 'HelloWorld',
          component: HelloWorld,
        },
      ],
    });
    

    App.vue

    <template>
      <div id="app">
        <router-view/>
      </div>
    </template>
    
    <script>
    export default {
     name: 'App',
     metaInfo: {
        title: "My Website - "+ route.name,
    },
    };
    
    </script>