Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here
Courses

Vue.js 3 + Laravel 11 + Vite: SPA CRUD

Vue Routes: Meta Title in Global Layout

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

avatar

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

avatar

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

avatar

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

avatar

**vue-router