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

What is the best way to overlay text onto a background image using Material UI's Card and CardMedia components?

Using the card component, I have successfully added a background image. However, I am facing difficulty in figuring out how to overlay text on top of this image. If anyone has suggestions or alternative methods, please feel free to share! <Card> ...

Tips for connecting elements at the same index

.buttons, .weChangeColor { width: 50%; height: 100%; float: left; } .weChangeColor p { background: red; border: 1px solid; } .toggleColor { background: green; } <div class="buttons"> <p><a href="#">FirstLink</a></ ...

"Stripe offers a variety of services including Stripe Payments, Connect, Linked Account, and Split Payment

I'm currently in the process of onboarding new users to our platform through Stripe. First, I initiate the creation of an account in Stripe: $this->stripe->accounts->create([ 'type' => 'express', ...

searching for unspecified information in node.js mongodb

I am encountering an issue while trying to retrieve data from the database after a recent update. The code snippet result.ops is not functioning as expected in MongoDB version 3.0. I am receiving undefined in the console output. Can someone guide me on the ...

Installing a package from a private repository using a different package name with npm

I'm looking to incorporate a module from a private GitHub repository into my project. To achieve this, I will execute the command npm install git+https://[API-KEY]:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b737c6e607 ...

Error: Unable to modify the value of a protected property '0' in the object 'Array'

I am facing a challenging issue with implementing a Material UI slider in conjunction with Redux. Below is the code for the slider component: import { Slider } from '@material-ui/core' const RangeSlider = ({handleRange, range}) => { ...

AngularJS is experiencing delays when processing subsequent $http delete requests, leaving them stuck in a

I am currently working on a project where I have a table displaying a list of objects, with each object having multiple child objects associated with it. The technologies I am using include Angular 1.2.20, Express 4.6.1, and Node 0.10.25. In the table, the ...

What could be causing the response data from an AJAX request to be in error instead of success?

My JSON data is securely stored on , and I can access it through a unique URL. Here is the specific URL: The JSON data found at the above URL is: { "glossary": { "title": "Suyog", "GlossDiv": { ...

Why React.js and webpack are restricting the use of var, let, const?

I'm facing a puzzling issue that I just can't seem to solve. Let me show you a snippet from my Graph.js file: class Graph extends React.Component { @observable newTodoTitle = ""; s = 40 The error in webpack is showing up like this: E ...

Error: Webpack module is not a callable function

I have been developing a backend system to calculate work shifts. I am currently facing an issue with posting user input using a module located in services/shifts. While the getAll method is functioning properly, I encounter an error when trying to post da ...

Tips for distinguishing the beginning and ending points of wrapped text in the Firefox browser

Within my work, I am utilizing a contentEditable span where I aim to position an element with position: absolute on the same line as the cursor. However, issues arise when text wrapping occurs - causing abnormal behavior at the start and end of wrapped lin ...

How can methods access variables from the Vuex store during function calls?

Within my Vue.js component, there is a v-select element. Upon user selection in this widget, the toDo function is triggered from the methods block. However, when attempting to access the value of the filters getter within this function, it consistently ret ...

JavaScript / AngularJS - Efficient Boolean Switching

My group of Boolean variables can toggle other variables to false when set to true. I am looking for a clean pattern for this approach, especially since the number of boolean variables may increase. angular.module("app", []) .controller("controller", ...

Implementing bind to invoke a function during an onClick Event

Here is a code snippet I have been working on that demonstrates how to handle click events on hyperlinks. The code features two hyperlinks named A and B. When hyperlink A is clicked, the console will log 'You selected A', and when B is clicked, ...

javascript passing a window object as an argument to a function

In Slider function, I am passing a window object that does not contain the body element. Additionally, my code only functions correctly on mobile screens. While debugging the code below: console.log(windows.document); If (!mySlider) {console.log(windows. ...

Struggling with passing data to a child component in React

I am currently working on a gallery project where users can click on an image to view it in a separate component using props. The images are sourced from a hardcoded array, and the challenge lies in connecting this data to the component accurately. I have ...

How can I modify all URLs in .htaccess to point to index.html while still preserving existing directories, since I am utilizing Vue-Router?

I created a web application using VUE CLI with Vue-Router functionality. In order to rewrite all requests to the index.html file, I added the following code: RewriteEngine On RewriteRule ^(.*)$ ./index.html [L] However, there is an issue with two folders ...

HTML/Javascript/CSS Templates: Keeping Tabs on Progress

I'm looking for templates that use notepad as an editor for html/javascript/css. I want to find a template that displays text or pictures upon clicking, like the example below: Sorry if this is a silly question, it's been 8 years since I last di ...

Issue with Vue JS: running the build command `npm run build` fails to generate the `index.html` file

While executing the command npm run build, I am facing an issue where it does not generate the index.html file in the dist/ directory. The purpose behind needing this index.html file is to deploy my Vue project on AWS EC2 at location (/var/www/html/). Can ...

Why do Vue/Nuxt Select field states come pre-set as valid?

My Nuxt.js form contains multiple HTML select elements, each with validation using Vuelidate. The validation is working correctly. Here is an example of one of the select boxes in my form: <select id="location" name="location" v-m ...