What is the best way to send a custom property through Vue router?

I'm currently working with a route instance:

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: MainContainer,
      redirect: '/news/list',
      children: [
        {
          path: 'advertisement/create',
          name: 'Create Advertisement',
          title: 'This is title of the page'
          component: CreateAdvertisement
        }
      ]
    }
  ]
})

While working on my component, I attempted to access this.$route and found that it only contained the properties name, path, and component, with no title property present. This led me to question: Is it possible to pass a custom property via Vue router? If so, what could be causing my attempt to fail?

Answer №1

To enhance the metadata, you can:

 const router = new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: MainContainer,
      redirect: '/news/list',
      children: [
        {
          path: 'advertisement/create',
          name: 'Create Advertisement',
          title: 'This is title of the page'
          component: CreateAdvertisement,
          meta:{
           // place your enhancements here
           additionalKey: additionalValue
          }
        }
      ]
    }
  ]
})

https://router.vuejs.org/guide/advanced/meta.html

Answer №2

Utilize the meta tag to manage additional data as shown in the example provided in the link below:

Live Fiddle

I am changing the Title using this.$parent.title.

const http404 = { 
template: '<div>http404 path is : {{$route.path}}</div>',
  mounted(){
    console.log(this.$route.path);
    this.$parent.title ="http404 Page";
  }
}
const index = { 
template: '<div>index path is : {{$route.path}}</div>',
  mounted(){
  this.$parent.title ="Index Page";
    console.log(this.$route.path);
  }
}
const panda = { 
  template: '<div>panda path is : {{$route.path}}</div>',
  mounted(){
  this.$parent.title ="panda Page";
     console.log(this.$route.path);
  }
}

const router = new VueRouter({
  mode: 'history',
  routes: [
  {
        path: "/",
        name: "root",
        redirect: '/index'
      },
      {
        path: "/index",
        name: "index",
        component: index
      },
      {
        path: "/panda",
        name: "panda",
        component: panda
      },
      //...
      {
        path: "**",
        name: "http404",
        component: http404
      }
    ]
})

new Vue({
router,
  el: '#app',
  data:{
  title:"NA"
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
<div>Page : {{title}}</div>
 <router-link to="/">Root</router-link> |
 <router-link to="/index">Index</router-link> |
 <router-link to="/panda">Panda</router-link> |
 <router-link to="/http404">http404</router-link>
  <router-view></router-view>
</div>

Answer №3

To customize a property in the child component, simply add the props to the children component declaration:

const router = new Router({
    routes: [
        {
            path: '/',
            name: 'Home',
            component: MainContainer,
            redirect: '/news/list',
            children: [
                {
                    path: 'advertisement/create',
                    name: 'Create Advertisement',
                    component: CreateAdvertisement,
                    props: {
                        title: 'Custom title for the page'
                    }
                }
         ]
      }
   ]
})

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

Is there a way to prevent my timer from resetting whenever I refresh the page?

Hey everyone, I'm new to coding and I could really use some help here. I have this code for a timer but I'm struggling to make it work properly even after refreshing the page. My goal is to keep the timer running smoothly, but I'm not sure w ...

How to show line breaks in MySQL text type when rendering in EJS

In my MySQL table, I have a column called PROJ_ABOUT with the type TEXT. I have inserted several rows into this column and now I am trying to display this information in my Express.js app using the ejs engine. <h2>About project</h2> <p> ...

Adjusting the transparency of numerous elements using JavaScript or jQuery

My task involves creating a large form where elements initially have an opacity of 0.5, and when a button is clicked, the opacity changes to 1.0. While I can achieve this using JavaScript, I want to find a more efficient way by avoiding individual if state ...

Javascript Calculator with Dual Input Fields

I have been given a task to create a calculator by tomorrow using Javascript. Unfortunately, I am currently taking a distance course and Javascript has just been introduced in this assignment. While I am familiar with HTML and CSS, Javascript is something ...

"Make your slides smooth and responsive with the unslick option in slick

Currently implementing the Slick Slider on a WordPress website. The slider is designed to display 3 columns at a screen size of 1024px and above. When the screen size drops below 1024px, the slider adjusts to show 2 columns, and on mobile devices, it swit ...

When attempting to add a new element to an array, the JSON key is mistakenly assigned a number instead of an array

I'm having trouble creating a JSON object that should look like this: { "sreddy-vm-1":["MyDatabase-1"], "sreddy-vm-2":["MyDatabase-2"], "sreddy-vm-3":["MyDatabase-3", "MyDatabase-4", "MyDatabase-5"] } However, the output I'm getting is diff ...

Sort the elements within the *ngFor loop according to the category upon clicking the button in Angular

Currently, I have a collection of items that I am iterating through using *ngFor. Above this list, there are category buttons available as shown in the HTML snippet below. My goal is to enable filtering of the list based on the category of the button click ...

Are you wondering about the correct way to install eslint-config-airbnb without encountering any "UNMET PEER DEPENDENCY"

➜ beslint git:(master) ✗ eslint -v v3.15.0 ➜ beslint git:(master) ✗ npm install -g eslint-config-airbnb eslint-plugin-jsx-a11y eslint-plugin-import eslint-plugin-react /Users/next/.nvm/versions/node/v7.5.0/lib ├── UNM ...

What could be the reason for the Laravel middleware CORS not functioning properly in conjunction with Vue

Currently, I am working with Laravel 5.7 as the backend and Vue.js as the frontend. To send HTTP requests from Vue to the Laravel backend, I decided to use the Laravel CORS package, which can be found at this GitHub link: https://github.com/barryvdh/larave ...

javascript display hide choose among

I am attempting to display another set of options when the user selects a specific item. For example, if the user selects "Products," then a new selection box should appear with different product types. See my code below: <html> <head> <m ...

methods for transferring information from a website to a smartphone using SMS

I am currently in the early stages of learning JavaScript and working on a project that involves creating a form (a web page) to send data to my mobile device via SMS when the submit button is clicked. However, I am unsure how to transfer data from JavaS ...

Can we improve the coding of this as it seems inefficient and uses up too much room?

Do you think there is a more efficient way to write this code? It seems quite impractical and takes up a lot of space. Essentially, it's about the random chance of obtaining a rarity, like acquiring an Uncommon sword. if (Math.random() * 100 < 100 ...

"Performing a MongoDB Node query within the time frame of 1 hour from

I am having trouble retrieving data with my query to find all objects within the last hour based on timestamps: Here is the schema I am using: var visitSchema = mongoose.Schema({ timestamp: { type: Date, default: Date.now }, userID: String, userName ...

"Simultaneously creating a Firebase user account and populating the database with user

My goal is to store new user information in my database using their unique user UID when they sign up through Firebase. Currently, my code is functioning properly, however, I am facing an issue where the name (which should be the created user UID) appears ...

React JS project experiencing issues with Material UI components not functioning properly

Here is a unique version of my app.js code: import React from "react"; import './App.css'; import {Button} from "@mui/material"; function App() { return ( <div className="App"> <h1>COVID-19 T ...

Angular ng-bind-html directive allows you to bind HTML content to an

I am attempting to utilize $interpolate and ng-bind-html in order to bind the data from my scope variable to an html string as outlined in this solution. However, I have encountered an issue where the ng-bind-html result does not update when the value of m ...

The TypeScript error occurs when attempting to assign a type of 'Promise<void | Object>' to a type of 'Promise<Object>' within a Promise.then() function

I'm currently working on a service to cache documents in base64 format. The idea is to first check sessionStorage for the document, and if it's not there, fetch it from IRequestService and then store it in sessionStorage. However, I've encou ...

Utilizing ReactJS to fetch data from Material-UI's <TableRow/> component upon selection - a comprehensive guide

I've integrated Material-UI's <Table/> (http://www.material-ui.com/#/components/table) component with <TableRow/> containing checkboxes in a ReactJS project. While I can successfully select rows by checking the boxes, I am struggling ...

Exploring the differences between server-side rendering and client-side rendering in Express using Pug

I find myself in a state of confusion when it comes to distinguishing between what is considered client-side and server-side. Currently, as I develop a website using Pug for my HTML pages without any external files being loaded into the client's brows ...

Using React and Ant Design: Sharing state between multiple <Select> components within a <Form> element

Just getting started with ReactJS and AntDesign. Currently, I am working on connecting a series of <Select> components to share state. The goal is for the selection made in the first dropdown to dynamically update the options available in the follow ...