How can I show a title when redirecting a URL in VUE JS?

My current setup includes a navigation drawer component that changes the title based on the user's route. For example, when navigating to the home page (e.g. "/"), the title updates to "Home", and when navigating to the profile page (e.g. /profile), the title becomes "Profile". However, if I directly access certain URLs like /profile or /profile/list, the title remains as the default value "TEST" instead of updating to "Profile". Would implementing a watch method on my route be a solution to this issue?

index.js

export const state = () => ({
  title: 'TEST',
})

export const getters = {
  getTitle: (state) => state.title
}

export const mutations = {
  setTitle(state, value) {
    state.title = value
  }
}

export const actions = {
  setTitle({ commit }, value) {
    commit('setTitle', value)
  }
}

NavigationDrawer.vue

<script>
export default {
  data: () => ({
    drawer: true,
    items: [
      {
        icon: 'mdi-home',
        title: 'Home',
        to: '/'
      },
      {
        icon: 'mdi-account',
        title: 'Profile',
        style: 'profile',
        links: [
          { title: 'Dashbord', to: '/profile/' },
          { title: 'Staff List', to: '/profile/list' },
          { title: 'Search', to: '/profile/search' },
        ]
      },
      // Additional items here...
    ],
  }),

  methods: {
    // UpdatePageTitle, toggleDrawer, isAdminChipVisible, isVisibleForRegularUser, isVisibleForHod, and isVisibleForHrAdmin methods imported from original text.
  },

  mounted() {
    const currentPath = this.$router.currentRoute.path
   const currentPageName = this.getCurrentPageNameByPath(currentPath)

   this.$store.dispatch("setTitle",currentPageName)
    this.$nextTick(() => {
      if (this.$vuetify.breakpoint.mdAndDown) this.drawer = false
    })

  },
}
</script>

<template class="nav-color-gradient">
  <v-navigation-drawer
    class="nav-color-gradient"
    v-model="drawer"
    :width="300"
    app
    dark
    fixed
    floating
  >
    // Navigation Drawer template code from original text...
  </v-navigation-drawer>
</template>

Answer №1

Here are two suggested approaches to accomplish this task :

1 - One way is to trigger the 'setTitle' action when each page is mounted. For instance, in the Profile.vue page, you can include the following code :

mounted(){
    // Assign the current page name to currentPageName, which is 'Profile' in this case
    this.$store.dispatch("setTitle",currentPageName)
}

2 - Another approach involves extracting the page name from the current route URL within the 'created' or 'mounted' method of the 'NavigationDrawer.vue' file, and then dispatching a new Action 'setTitle' by providing the extracted page name :

mounted(){
   // your code 
   ......
   // 1 - Obtain current path from the router
   const currentPath = this.$router.currentRoute.path
   // 2 - Search for the page name in the items array using a custom method,
   // such as (getCurrentPageNameByPath) for performing this operation
   const currentPageName = getCurrentPageNameByPath(currentPath)
   // 3 - Dispatch the current page name
   this.$store.dispatch("setTitle",currentPageName)
}

methods : {
   getCurrentPageNameByPath(path){
      let path = '/profile/'
      let currentPageName = ''

      for(let item of items){
         if(item.links) {
             for(let nestedItem of item.links ){
                 if(nestedItem.to == path) {
                    currentPageName = item.title;
                    break;
                 }
            }  
         }else {
              if(item.to == path) {
              currentPageName = item.title;
              break;
         }
       }
     }

     console.log(currentPageName)
     return currentPageName
   }

}

Answer №2

Utilize the beforeRouteEnter hook to enhance your routing experience,

beforeRouteEnter (to, from, next) {
// document.title = to.title; // Feel free to set page title here as well 
store.dispatch("setTitle",to.title);
next();

}

Remember to import store in order to access it within the router hook

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

A space designated for numerous receivers

Is there a way to create a field that contains other elements, similar to sending messages to multiple users in a social network? https://i.stack.imgur.com/P9e24.png I attempted to understand the code for this, but it's quite complex. If anyone could ...

The challenge of mocking methods/hooks remains when utilizing `jest.spyOn` in Jest

I am attempting to create mock methods and hooks in a file, then import those mock functions as needed in my test files. useMyHook.jsx const useMyHook = () => { const [val, setVal] = useState(200) return { val } } export { useMyHook } Hello.jsx: ...

Create unique identifiers for the TD elements of Viz.js that will be displayed within the SVG elements

Below is the DOT code snippet in Viz.js that I am working with: digraph G { node [fontname = "font-awesome"]; 17 [id=17, shape="hexagon", label=<<TABLE BORDER="0"> <TR><TD>undefined</TD></TR> <TR><TD>[47-56]< ...

Angular successfully compiled without any issues despite the explicit cast of a number into a string variable

As I delve into the initial concepts of Angular, I have come across a puzzling situation. Here is the code snippet: import { Component } from '@angular/core'; @Component({ selector: 'sandbox', template: ` <h1>Hello {{ nam ...

The Jquery flot plugin is failing to plot the graph accurately based on the specified date

I am currently working on plotting a graph using the jquery flot plugin with JSON data. Here is what I need to do: Upon page load, make an AJAX call to receive JSON data from the server. From the received JSON, add 'x' and & ...

Implementing image-based autocomplete in a search bar within an MVC framework

Seeking assistance to implement a unique feature for my MVC application. I aim to create a search box that suggests images based on user input rather than text. The functionality involves matching the user's input with the "Title" property in an Ent ...

Enforce the splicing of the ng-repeat array with the utilization of track by

Our app incorporates a task list that can potentially grow to a substantial size. The main task list is accompanied by a sidebar, where selected tasks can be edited using a different controller (TasksSidebarCtrl instead of TasksCtrl which handles the list ...

Calculating the sum() of a specific attribute in Loopback without the need to iterate through every instance of the object

Within my DummyModel, there are attributes named attOne, attTwo, and attThree. If we want to retrieve all instances of attOne, we can utilize the following query: DummyModel.find({where: {attTwo: 'someValue'}, fields: {attOne: true} }); The ab ...

Variety of part ingredients

In my component, I have a button and include another component which also contains a button. How can I align these two buttons next to each other without using absolute positioning? When I try positioning them using absolute right and top values, the lay ...

A fresh perspective on incorporating setInterval with external scripts in Angular 7

Incorporating the header and footer of my application from external JavaScript files is essential. The next step involves converting it to HTML format and appending it to the head of an HTML file. private executeScript() { const dynamicScripts = [this.app ...

Error message: Unable to access property 'post' from undefined - Angular 2

Here is the snippet of code in my component file: import { Component, Injectable, Inject, OnInit, OnDestroy, EventEmitter, Output } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import & ...

Unlock the power of VueJS with advanced checkbox toggling for array data

I have encountered an issue while working with VueJS regarding the implementation of two features for a set of checkboxes. Initially, the checkboxes are generated dynamically. I am in need of a master 'toggle' checkbox that can toggle the stat ...

What is the best way to link an image in a React Component NPM module?

I have developed a date picker component in React and I'm currently working on uploading it to NPM. The component utilizes an external SVG file, but I am encountering issues with referencing that SVG file properly. Here's the structure of my fil ...

What are the steps to ensure compatibility with relative paths when transitioning from v5 to v6?

In my application, there are scenarios where multiple routes must pass through a component before rendering specifics. Additionally, there are situations where something is displayed for the parent route and then divided for the children. It's crucia ...

I'm having trouble showing data from an API in my Vue.js application using v-for

I am struggling to fetch and display data from an API in my Vue.js application. Although the API seems to be functioning correctly when I check using console.log(), I am unable to populate the table with the retrieved data. Since I am new to Vue.js, I am u ...

Incorporate a button within a listview on Kendoui to trigger the opening of a modal window

I am seeking assistance on how to insert a button on each element of a Listview (PHP/Json) result. When clicked, this button should open a modal window where the customer can input reservation details such as Date, Adults, and Children. Below is the JavaSc ...

Include a button alongside the headers of the material table columns

I am looking to customize the material table headers by adding a button next to each column header, while still keeping the default features like sorting and drag-and-drop for column rearrangement. Currently, overriding the headers requires replacing the e ...

Navigate within a div using arrow keys to reposition another div

As a newcomer to JavaScript, I am facing some challenges. My goal is to use arrow keys to move a small div inside a larger div. However, the code below is not functioning as expected. Here is the HTML and CSS: <div id="rectangle"> <div id="s ...

Quasar's line break is displaying incorrectly as <br /> instead of a traditional line break

return str + '<br />' + data I am attempting to display this in Quasar, however it is showing as text rather than a line break. Is there something I might be overlooking? ...

Unable to view the image in browsers other than Internet Explorer

On a webpage, there is a feature where clicking on the "Add More" link should display an input box and a "Delete" button image. Surprisingly, this functionality works perfectly on IE browsers, but not on Mozilla or Chrome. In non-IE browsers, only the text ...