Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue.js get route name in App.vue

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>
like image 829
Murasaki Aikon Avatar asked Feb 04 '23 00:02

Murasaki Aikon


1 Answers

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()
})
like image 124
Ru Chern Chong Avatar answered Feb 06 '23 14:02

Ru Chern Chong