Skip to main content

Vue Routes: Meta Title in Global Layout

Lesson 13/27 2 min read
Autoplay

Lesson Overview

- Adding meta information to routes
- Creating dynamic page titles
- Using computed properties with router
- Implementing global layout variables

In this lesson, we will see how we can make global variables. Now on every page, we have a page heading that only says Dashboard. Let's change that to be dynamic for every page.

dynamic heading


There are a few ways to do that. We will pass that text as a parameter. Inside the App layout file first, let's change the Dashboard text to a variable.

resources/js/layouts/App.vue:

<template>
// ...
<!-- Page Heading -->
<header class="bg-white shadow">
<div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
Dashboard
{{ currentPageTitle }}
</h2>
</div>
</header>
// ...
</template>

We will make this variable a computed property.

resources/js/layouts/App.vue:

<template>
// ...
</template>
 
<script setup>
import { computed } from 'vue';
 
const currentPageTitle = computed(() => 'New computed dashboard')
</script>

After visiting any page you will that the heading text is changed now.

changed heading text

Now let's make text dynamic for every page. For this, we will add a new variable meta to the route.

resources/js/routes/index.js:

// ...
const routes = [
{
path: '/',
name: 'posts.index',
component: PostsIndex,
meta: { title: 'Posts' }
},
{
path: '/posts/create',
name: 'posts.create',
component: PostsCreate,
meta: { title: 'Add new post' }
},
]
// ...

To access this meta variable in the main App layout, we need to import routes Composable and use them to get the meta with the title.

resources/js/layouts/App.vue:

<template>
// ...
</template>
 
<script setup>
import { computed } from 'vue';
import { useRoute } from 'vue-router'
 
const route = useRoute()
 
const currentPageTitle = computed(() => 'New computed dashboard')
const currentPageTitle = computed(() => route.meta.title)
</script>

That's it. After visiting any page you will heading is changing according to that page that was set in the meta.

dynamic heading

Comments & Discussion

F
Fiestus ✓ Link copied!

Hello, thank you for the lessons! It would be helpful to know how we can add translation to meta variables.

PK
Povilas Korop ✓ Link copied!

For translations between Laravel and Vue, I would probably use this package: https://github.com/xiCO2k/laravel-vue-i18n

R
Rangoh ✓ Link copied!

Wahou! All fundamental knowledges required for view-router is explained in such an easy way. Thanks!

J
jwinder ✓ Link copied!

**vue-router

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.