What is the best method for transferring properties to the parent component using Vue router?

I have a multi-step form that each step has a different header structure.

The only variation in the header among the steps is the wording, which changes as you progress through the steps.

I am looking for a way to achieve this using Vue Router:

      path: '/form',
      name: 'Form',
      component: Form,
      children: [
        {
          path: 'step1',
          component: FormStep1,
          propsForParent: {
            title: "myTitle In Header In Form Component"
          },
        },
        {
          path: 'step2',
          component: FormStep2,
          propsForParent: {
            title: "myTitle is different In Header In Form Component"
          },
        }
      ]

So, when navigating to form/step1, I want the form component to receive the designated title props set in my child configuration above, and so forth for other steps.

I aim to avoid dealing with this logic in the parent component or having the child components communicate with the parent via events or Vuex. I'm seeking a more elegant solution within Vue Router itself.

Any suggestions?

Answer №1

Utilize route meta data:

path: '/form',
name: 'Form',
component: Form,
children: [
  {
    path: 'step1',
    component: FormStep1,
    meta: {
      title: "Custom Title for Step 1"
    },
  },
  {
    path: 'step2',
    component: FormStep2,
    meta: {
      title: "Different Title for Step 2"
    },
  }
]

In your parent component:

computed: {
  title () { this.$route.meta.title }
}

If you want to pass title as a prop to the parent component:

routes: [{
  path: '/form',
  name: 'Form',
  component: Form,
  props (route) => {
    return {
      title: route.meta.title
    }
  }
  children: [ ...

To make title inheritable, use:

const matched = route.matched.slice().reverse().find(route => route.meta.title)
matched.meta.title

Note: Using slice() creates a copy of an array to avoid modifying the original one.

Answer №2

You're so close to the solution! Just remember to emit from the child to the parent using the prop value received.

      path: '/form',
      name: 'Form',
      component: Form,
      children: [
        {
          path: 'step1',
          component: FormStep1,
          props: {
            title: "myTitle In Header In Form Component"
          },
        },
        {
          path: 'step2',
          component: FormStep2,
          props: {
            title: "myTitle is different In Header In Form Component"
          },
        }
      ]


//In FormStep2 and FormStep1 components
created() {
    this.$emit('childinit', this.title);
  },


//Inside Form component
methods: {
    onChildInit( value ){
      this.title = value;
    }
  }

To streamline your code, consider adding another layer of children within your router setup. This will eliminate the need to emit from every child component. Here's an example from a project I'm currently working on, notice the step prop being passed around.

//Within my timelineBase component, I listen for onChildInit, create a method to extract value from the child, and use it in the layout to communicate with pageStepper.

<router-view v-on:childinit="onChildInit" :key="componentKey"></router-view>
<pageStepper :step="pageStepper"></pageStepper>

//Component has these props. props: ['mode','step','componentKey'],

Here are my routes:

const router = new VueRouter({
    routes: [
      {
        path: '/',
        component: Layout,
        children: [
          {
            path: '',
            component: homepage,
            props: { cssClass: '' },
          },
          {
              name: 'addTimeline',
              path: 'timeline',
              props: { mode:'add', step: 1, componentKey: 0 },
              component: timelineBase,
              children:
              [
                  {
                    path: 'add',
                    component: timeline,
                    props: { mode:'add', step: 1, componentKey: 1},
                  },
                  {
                      name: 'updateTimeline',
                      path: ':id/update',
                      component: timeline,
                      props: { mode:'update', step: 1, componentKey: 2 }
                  },
                  {
                      name: 'addEvent',
                      path: ':id/event/add',
                      component: addevent,
                      props: { mode:'add', step: 2, componentKey: 3 }
                  },
                  {
                      name: 'editEvent',
                      path: ':id/event/edit/:event_id',
                      component: editevent,
                      props: { mode:'update', step: 2, componentKey: 4 }
                  },
                  {
                      name: 'previewTimeline',
                      path: ':id/preview',
                      component: preview,
                      props: { step: 3, componentKey: 5 }
                  },
              ]
          },


        ]
      }
    ]
});

Answer №3

There's room for a slight enhancement to execute it in a more refined manner.

In line with Squiggs.' suggestion, we could trigger the childinit in each child component, but continuously including the emit code in every child component may become laborious.

Nonetheless, a viable solution could involve using a mixin. By creating a mixin that emits the childinit along with its properties, and then importing and employing this mixin in each child component, we can address this issue effectively.

// mixin
export default {
  props: {
    title: {
      type: String,
      default: '',
    },
  },
  created() {
    this.$emit('childinit', this.title)
  },
}

// parent
<template>
  <div class="wrapper">
    <router-view @childinit="childInit"/>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: '',
    }
  },
  methods: {
    childInit(title) {
      this.title = title
    },
  },
}
</script>


// child
<script>
import TitleMixin from './mixins'

export default {
  mixins: [TitleMixin],
}
</script>

Answer №4

Another option is to utilize Vuex or localStorage for handling props. Keep in mind that values stored in Vuex will be cleared upon refreshing.

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

Performing an API GET request in a header.ejs file using Node.js

Looking to fetch data from an endpoint for a header.ejs file that will be displayed on all routed files ("/", "/news" "/dogs"). Below is my app.js code: // GET API REQUEST var url = 'https://url.tld/api/'; request(url, function (error, response, ...

Tips for transmitting form information in a fetch call

As I was developing a nodejs server, I encountered an issue with the POST call that involves sending form input data to a remote server. Despite everything else working fine, the form data was not being received by the server. Below is the code snippet in ...

Make sure to verify a user's "clearance level" before entering a page

Recently delving into the world of node.js, I encountered a simple issue: In my routes file, there is a function that verifies if a user is authenticated. function isLoggedIn(req, res, next) { if(req.isAuthenticated()){ console.log(req.user); ...

Translate unknown provider in Angular using $translateProvider

Here is the situation I am facing: I am working on an Ionic project and I want to implement internationalization using angular-translate. To achieve this, I have added angular-translate.min.js to my project: <script src="lib/ionic/js/ionic.bundle.js"&g ...

I am seeking to redirect to a different page within an ejs template by clicking on a link

I am having trouble navigating to the next page using a link and keep getting a 404 error. I recently switched my template from jade to ejs. <html> <body> <div> <ul style="color:white; float: right;" class="nav navbar-nav ...

Utilizing Vue class-style components for creating a recursive component

I'm currently working with a class-style component using the vue-property-decorator plugin. I want to create a recursive component that can use itself within its own structure. Here's a snippet of my code: <template> <ul> <li& ...

Tips for creating a consistent format based on test cases

var years = Math.floor(seconds / (3600*24*365)) seconds -= years*3600*24*365 var days = Math.floor(seconds / (3600*24)) seconds -= days*3600*24 var hrs = Math.floor(seconds / 3600) seconds -= hrs*3600 var minutes = Math.floor(seconds / 60) ...

Implementing a PHP button update functionality sans utilizing an HTML form

I need a way to update my database with just a click of a button, without using any forms or POST requests. Most examples I've seen involve updating through forms and the $_POST method. Is there a simpler way to update the database by directly click ...

I have successfully managed to populate the Google Apps Script listbox based on the previous listbox selection for two options, but unfortunately, I am encountering issues

Struggling to set up 3 list boxes that populate based on each other? At the moment, I have one list box fetching data from a spreadsheet. Could someone assist me in configuring it so that the second list box populates based on the first, and a third list b ...

Column alignment issue detected

Can you help me with aligning the data in my column status properly? Whenever I update the data, it doesn't align correctly as shown in the first image. https://i.stack.imgur.com/300Qt.png https://i.stack.imgur.com/4Dcyw.png $('#btn_edit' ...

Utilize a class method within the .map function in ReactJS

In my ReactJS file below: import React, { Component } from "react"; import Topic from "./Topic"; import $ from "jquery"; import { library } from '@fortawesome/fontawesome-svg-core' import { FontAwesomeIcon } from '@fortawesome/react-fontaw ...

What is the best way to extract the JSON data from a client-side GET request response?

Here is my request from the client side to the server in order to retrieve JSON data. fetch("/" + "?foo=bar", { method: "GET", }).then(response => { console.log(" ...

Creating a mind map: A step-by-step guide

I'm currently developing an algorithm to create a mind map. The key focus is on organizing the nodes intelligently to prevent any overlap and ensure a visually pleasing layout. Take a look at this snapshot (from MindNode) as an example: Any suggestio ...

Manage how child components are displayed in React in a dynamic manner

My React parent component contains child components that are rendered within it. <div id="parent"> {<div style={{ visibility: isComp1 ? "visible" : "hidden" }}><MyComponent1 {...props}/></div>} ...

Java servlet is unable to interpret the name of an html select tag

Currently, I am implementing a feature where table rows with select boxes are added dynamically and the values of these select boxes are retrieved in a servlet. The process of adding the select boxes is functioning properly; however, when attempting to ret ...

Fixing a menu hover appearance

I recently encountered a small issue with the menu on my website. When hovering over a menu item, a sub-menu should appear. However, there seems to be a slight misalignment where the submenu appears a few pixels below the actual menu item. Check out the w ...

Extracting every other value from an array can be achieved by iterating through the

Hi, I'm looking to create a function that will log every other value from an array. For example, if we have: var myArray = [1,45,65,98,321,8578,'orange','onion']; I want the console.log output to be 45, 98, 8578, onion... Does ...

Is it possible to utilize href alongside the urlRouterProvider?

Within my angularjs application, I opted to switch from using ngRoute (routeProvider) to ui.router (urlRouterProvider) module and stateProvider for transitioning between different states in the app. However, I recently discovered that ui-router only suppo ...

Encountering a console error: Prop type validation failed for the `Rating` component with the message that the prop `value` is required but is currently `undefined`

I am encountering a proptype error which is causing an issue with the URL display on my Chrome browser. Instead of showing a proper address, I am seeing the URL as undefined like this: http://localhost:3000/order/undefined Instead of undefined, I should h ...

Steps for updating a property of an object using a function

I am working on a function that resets the deepest value of an object with variable depth to 0. I need this function to update the object's property outside of its scope. var data = { '1': { '10000': { ...