What is the best way to determine the current active route in Vue.js?

I am working on a simple Vue application:

App.vue:

<template>
  <v-app>
    <v-navigation-drawer
      app
      v-model="drawer"
      :mini-variant.sync="mini"
      permanent
      color="secondary"
      dark
    >
      <v-list-item class="px-2 user-block">
        <v-list-item-avatar>
          <div class="avatar">JL</div>
        </v-list-item-avatar>

        <v-list-item-title>John Leider</v-list-item-title>

        <v-btn icon @click.stop="mini = !mini">
          <v-icon>mdi-chevron-left</v-icon>
        </v-btn>
      </v-list-item>

      <v-divider></v-divider>

      <v-list dense>
        <v-list-item
          v-for="item in items"
          :key="item.title"
          :href="item.link"
          @click.stop="title = item.title"
        >
          <v-list-item-icon>
            <v-icon>{{ item.icon }}</v-icon>
          </v-list-item-icon>

          <v-list-item-content>
            <v-list-item-title>{{ item.title }}</v-list-item-title>
          </v-list-item-content>
        </v-list-item>
      </v-list>
    </v-navigation-drawer>
    <v-app-bar app light>
      <div class="d-flex align-center">IFRS 9: {{ title }}</div>

      <v-spacer></v-spacer>
    </v-app-bar>

    <v-main>
      <router-view />
    </v-main>
  </v-app>
</template>

<script lang="ts">
import Vue from 'vue'
import router from './router'

export default Vue.extend({
  name: 'App',

  created() {
    const currentPath = router.currentRoute.path
    const activeItem = this.items.find((m) => m.link === currentPath)
    console.log(activeItem?.title)
    this.title = activeItem ? activeItem.title : 'Home'
  },

  data: () => ({
    drawer: true,
    items: [
      { title: 'Home', icon: 'mdi-home', link: '/' },
      { title: 'About', icon: 'mdi-help', link: '/about' },
    ],
    mini: true,
    title: '',
  }),
})
</script>

<style lang="sass">
@import '~vuetify/src/styles/settings/_variables'

.avatar
  background-color: #FFFFFF
  color: #6D2077
  font-weight: bold
  width: 48px
  height: 48px
  line-height: 48px

.user-block
  height: 64px

@media #{map-get($display-breakpoints, 'sm-and-down')}
  .user-block
    height: 56px
</style>

router/index.ts:

import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes: Array<RouteConfig> = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ '../views/About.vue'),
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

export default router

In the code above, I am attempting to dynamically change the value of title based on the current route path but it always displays as 'Home'.

Can anyone help me identify what I am doing incorrectly?

P.S. I'm still learning about Vue.

Answer №1

When working with the App.vue file, which is the highest level component in your Vue project, it's recommended not to set up the title in the created lifecycle hook. Instead, consider using a 'watcher' to keep track of changes to the $route value. Here's an example implementation:

export default Vue.extend({
  name: "App",
  //...
  watch: {
    $route(newRouteValue) {
      console.log(newRouteValue); // {name: "About", meta: {...}, path: "/about", hash: "", query: {...}, ...}
    },
  },
});

By implementing this code, you can ensure that the title gets updated appropriately as users navigate through different pages of your web application.

For more information on watchers, refer to the official documentation here: https://v2.vuejs.org/v2/guide/computed.html#Watchers

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

Attempting to use Vue.js for playing MP3 files

Motive: My objective is to incorporate a background sound into my project using a local file that can be played and paused. While loading an external URL file works fine and allows for play/pause functionality, I am encountering issues with the local fil ...

What could be causing the inner array typescript to be inaccessible in an Angular 5 application?

Below are the JSON definitions that I am working with: export class Company { name: string; trips : Trip[] = []; } export class Trip{ id: number; name: string; } Within the component, there is a method that contains the ...

Modifying the menu with Angular 4 using the loggedInMethod

Struggling to find a solution to this issue, I've spent hours searching online without success. The challenge at hand involves updating the menu item in my navigation bar template to display either "login" or "logout" based on the user's current ...

Create a custom hook that encapsulates the useQuery function from tRPC and provides accurate TypeScript typings

I have integrated tRPC into a project that already has API calls, and I am looking to create a separate wrapper for the useQuery function. However, I am facing challenges in getting the TypeScript types right for this customization. My Objective This is w ...

Angular 2 partial static routing parameters with customizable features

Can an angular 2 routing configuration include a partial-static parameter? Currently, I am using a classic parameter setup like this: const routes: Routes = [ { path: ':type/fine.html', pathMatch: 'full', redirectTo: &ap ...

How can you ensure the dynamic search parameter is accurately configured within the URL?

**Is the dynamic search parameter correctly set in the URL? Should I be using backticks or other syntax? I want to search for objects within a backend URL endpoint based on user input. https://codesandbox.io/s/onscroll-izfjoc?file=/index.html** people: ...

Exploring type delegation in TypeScript

Here is a scenario where I am using the builder pattern in my code: export class ValidationBuilderBase implements IValidationBuilder { public isRequired(): IValidationBuilder { const validationResult = Validators.required(this.baseControl); ...

Swap out the img tags sourced from the headless cms with the Next Image component

Currently, I am developing a headless WordPress marketing/commerce application with Next.js (hosted on Vercel). My goal is to parse incoming content bodies in order to dynamically replace img tags with the Next/Image Image component. If anyone has suggesti ...

How can TypeScript be used to define an onClick event that can also be triggered by keyboard input?

In the React Typescript guide, it suggests typing a click event as follows: https://github.com/typescript-cheatsheets/react-typescript-cheatsheet#basic-prop-types-examples onClick(event: React.MouseEvent<HTMLButtonElement>): void; However, buttons ...

"An issue has been identified where TSLint and VSCode fail to display red underlines in

I am currently working on a single .ts file where I am experimenting with configuring tslint and tsconfig. To test the configuration, I intentionally added extra spaces and removed semicolons. Despite running the command tslint filename.ts and detecting e ...

What could be causing the issue with the focus not being activated when clicking on the input field in Vue?

I am facing an issue where I have to click twice in order to focus on a specific input field, and I'm having trouble setting the cursor at the end of the input. I attempted to use $refs, but it seems like there may be a deeper underlying problem. Any ...

Require fields in TypeScript interfaces only for array types

Is there a way to make only array type interface fields required, not all of them? The Required operator currently makes every field mandatory, but I specifically need just the array fields to be required. ` interface IExample { a: number, b?: str ...

What is the best way to handle waiting for a request and user input simultaneously?

Imagine a scenario where a component loads and initiates an asynchronous request. This component also includes a submit button that, when clicked by the user, triggers a function that depends on the result of the initial request. How can I ensure that this ...

Is it considered bad practice to assign a value to a Vuex property directly in an action rather than using a mutation for the change

Currently, I have a Vuex action that performs a GET request and then assigns the response to a Vuex property: async getUserServers({commit, state, dispatch}, userId){ try { let response = await axios.get("/servers/" + userId) state.serv ...

What causes Node.js to crash with the Headers already sent Error while managing errors in Express?

My current project involves using Express to set up an API endpoint for user registration. However, I've encountered a problem where sending a request that triggers an error to this API endpoint causes my node.js server to crash. The specific message ...

zod - Mastering the Art of Dive Picking

Working with zod and fastify, my UserModel includes the username and device properties. The username is a string, while the device consists of "name", "id", and "verified" fields in an object (DeviceModel). For the sign-up process, I need to return the co ...

Implement Placeholder feature in ng2-ckeditor with the combination of Typescript and Angular 2.0

I am encountering an issue while trying to add the placeholder plugin to the CKEditor toolbar. When I include extraPlugins:'placeholder' in the CKEditor configuration, I receive the following error - Error: [CKEDITOR.resourceManager.load] Resou ...

What is the best method to merge two arrays into a single array of objects?

Is it possible to utilize an ngFor directive instead of duplicating the <table> element twice? (Note: I considered consolidating all items into objects within a single array for mapping purposes (each object containing a variable, label, and value) ...

Function returning promise asynchronously, but caller function failing to resolve the promise

I have been researching similar items without success and I realize that I need a better understanding of promises, but I am facing some challenges. My project involves Ionic 4/Angular 8 with an Azure-based backend. I am trying to display images from Azur ...

How can we assign dynamic unique IDs to HTML elements within a for..of loop in TypeScript?

Within my array, I am using a for..of TypeScript loop to dynamically add identical HTML elements. Each element needs to have a unique ID. Is it feasible to achieve this directly within the for..of Typescript loop? The code snippet is as follows: for (le ...