Obtaining the route name in Vue.js within the App.vue component

After utilizing vue-cli with webpack to construct the vue project, I incorporated vue-meta-info for SEO purposes.

I am facing an issue in setting up the page title using templates and route names. Unfortunately, I am unable to access the variable in the router.

router/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>

Answer №1

To easily update the title of all pages in your website, you can utilize the router's beforeEach() helper function.

For example, you can define the routes in a file named routes.js:

import Foo from '@/components/Foo'

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

In your main Javascript file, such as app.js or main.js, you can include the following code. This will ensure that each page updates its title accordingly:

import router from '@/routes'

// Add your other JavaScript code here

router.beforeEach((to, from, next) => {
  document.title = `My Website - ${to.meta.title}`
  next()
})

Answer №2

To change the title from every component to the root component, one approach is using $on .... $emit,

const Door = { template: '<div>Door</div>',
mounted: function () {
    vm.$emit('title', this.$route.name);
    } 
  }
const Bedroom = { template: '<div>Bedroom</div>',
mounted: function () {
      vm.$emit('title', this.$route.name);
    } 
  }
const Kitchen = { template: '<div>Kitchen</div>',
mounted: function () {
      vm.$emit('title', this.$route.name);
    } 
  }
const Hall = { template: '<div>Hall</div>',
mounted: function () {
      vm.$emit('title', this.$route.name);
    } 
  }

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/', component: Door, name:"You are in door"},
    { path: '/bedroom', component: Bedroom, name:"You are in Bedroom"},
    { path: '/kitchen', component: Kitchen, name:"You are in kitchen"},
    { path: '/hall', component: Hall, name:"You are in hall"},
  ]
})

var vm = new Vue({
router,
  el: '#app',
  data: {
    msg: 'Hello World',
    title:'no title set'
  },
  mounted: function(){
  this.$on('title', function (title) {
    this.title = title;
  })
  }
})
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <div>Title : {{title}}</div>
  <router-link to="/">Door</router-link>
  <router-link to="/bedroom"> | Bedroom</router-link>
  <router-link to="/kitchen"> | Kitchen</router-link>
  <router-link to="/hall"> | Hall</router-link>
  <router-view></router-view>
</div>

View working fiddle here

Alternatively, you can utilize $parent,

const Door = { template: '<div>Door</div>',
mounted: function () {
      this.$parent.title = this.$route.name;
    } 
  }
const Bedroom = { template: '<div>Bedroom</div>',
mounted: function () {
      this.$parent.title = this.$route.name;
    } 
  }
const Kitchen = { template: '<div>Kitchen</div>',
mounted: function () {
      this.$parent.title = this.$route.name;
    } 
  }
const Hall = { template: '<div>Hall</div>',
mounted: function () {
      this.$parent.title = this.$route.name;
    } 
  }

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/', component: Door, name:"You are in door"},
    { path: '/bedroom', component: Bedroom, name:"You are in Bedroom"},
    { path: '/kitchen', component: Kitchen, name:"You are in kitchen"},
    { path: '/hall', component: Hall, name:"You are in hall"},
  ]
})

new Vue({
router,
  el: '#app',
  data: {
    msg: 'Hello World',
    title:'no title set'
  }
})
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <div>Title : {{title}}</div>
  <router-link to="/">Door</router-link>
  <router-link to="/bedroom"> | Bedroom</router-link>
  <router-link to="/kitchen"> | Kitchen</router-link>
  <router-link to="/hall"> | Hall</router-link>
  <router-view></router-view>
</div>

View working JSFiddle here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to download multiple files using a single ajax call upon success of a click function?

In my file, there are 2 anchor tags with their respective href links. I am triggering both anchor tags at ajax call success. <a id="exportExcelFatturaIcon" href ="${createLink(action: 'downloadExcel', params: [fileName:excelFileName])}" hidde ...

Implementing Title Attribute in Grid View Template Field

I have implemented a Grid View with a "TemplateField" that includes properties for Header Text and SortExpression set to true. Upon inspecting the browser, I noticed that it generates an anchor element with some JavaScript. How can I add a title tag to t ...

Adding a class to a navigation item based on the route path can be achieved by following

I am currently working on a Vue.js project and I have a navigation component with multiple router-links within li elements like the example below <li class="m-menu__item m-menu__item--active" aria-haspopup="true" id="da ...

Sorting a list with anchor tags alphabetically using Javascript/JQuery

Here is a list of services: <ul id="demoOne" class="demo"> <li><a href='http://site/Service.aspx?shId=1154'>Copy service for files from folder 12</a></li> <li><a href='http://site/Service.aspx? ...

Struggling to retrieve the JSON information, but encountering no success

Here is the javascript code snippet: $.getJSON("validate_login.php", {username:$("#username").val(), password:$("#password").val()}, function(data){ alert("result: " + data.result); }); And here is the corresponding php code: <?ph ...

What is the best way to transfer Flow type properties from one React component to another?

I'm in the process of developing a component that will wrap another component known as Button. The tricky part is that the library where Button is defined does not expose the type of its properties. In order to properly assign types to my component, ...

Tips for leveraging OOP to eliminate redundant code repetition

How can I avoid repeating code when displaying multiple quizzes on the same page? Currently, I have a JavaScript function that duplicates everything for each quiz, with only a few variables changing in the second function. The problem arises when I need t ...

AngularJS: Error - Angular object is undefined

Hello! I am currently working on a project to develop a simple App using c# WebAPI and AngularJS. Unfortunately, I have encountered an error in the console which is preventing the web app from functioning properly. Here is a snippet of my Index.html file: ...

*Decoding the Mystery of $t in Vue.js*

My first experience working with Vue.js and I am unsure about the usage of $t. I came across some code that looks like this: <li class="category-filter__back"> <button class="category-filter__button" @click="back(categoryPath)"> ...

Every time I attempt to log in, the code keeps generating an error message net::ERR_EMPTY_RESPONSE. If successful, it should redirect to the

The code is producing a net::ERR_EMPTY_RESPONSE error when attempting to log in. The username and password are hardcoded. I simply want the admin to input their credentials on the Employee.html page, and if they match the ones in the main.js file, redirec ...

Editable Vue template that can be customized by the user

I have implemented a feature in my application where users can customize templates for different functionalities such as Invoices, Emails, etc. I want to allow the user to edit these templates by simply dragging and dropping elements. Currently, I am using ...

Adjust the path-clip to properly fill the SVG

Is there a way to adjust the clip-path registration so that the line fills correctly along its path instead of top to bottom? Refer to the screenshots for an example. You can view the entire SVG and see how the animation works on codepen, where it is contr ...

Accessing Elasticsearch from Kibana without the need for authentication and sending requests freely

Currently, I am in the process of developing a plugin for Kibana with the intention of establishing communication with Elasticsearch, utilizing Shield for security measures. Thus far, my approach has involved sending requests through the server with code ...

Why do browsers fail to cache Java scripts (Ajax) properly?

After creating a cascade drop-down list box with JQuery, the user can choose a state from the first drop-down and then the second drop-down will be filled with the relevant cities based on the selected state. However, I am facing an issue with caching in ...

What is the proper way to utilize a filtered object based on its properties within an Angular controller?

Currently, I am working on developing a stacked graph along with its associated table. To retrieve the necessary JSON data, I am utilizing $http.get() and then assigning it to $scope.dataset. Here's a snippet of the HTML: <input ng-model="_search ...

Thorax.js bower installation issue

After following the instructions in this guide: https://github.com/walmartlabs/thorax-seed/blob/master/README.md, I ran into an unexpected issue on my Windows machine. When running npm start It seems like bower is doing a lot of work (presumably loading ...

What are the reasons for the various methods available for importing my JS code?

Here is the structure of my folders: --public ----frontend.js --views ----fontend.ejs The frontend.js file is located inside the public folder, while the frontend.ejs file is in the views folder. In my HTML / EJS file, I included the JavaScript (fronten ...

Is it better to include the Google Analytics code in the master page or on every individual page of an asp.net

Looking for a way to track every page on my website effectively. Should I insert the Analytics tracking code in each aspx page inherited from the master page, or is it sufficient to place it only in the master page to track all inherited pages? ...

What is the process for delivering a promise?

In the context of my Angular application, I am facing a requirement where the method getData() must consistently return a promise. Should data be present in local storage and not null, it should be returned as a promise without requiring the $http.get func ...

Efficiently transferring time values from dynamically created list items to an input box using JavaScript

Is there a way to store a dynamically generated time value from an li element into an input box using JavaScript? I have a basic timer functionality on my website that includes starting, stopping, pausing, taking time snaps, and resetting them. These time ...