Will the nested routes components be considered children of the parent route's component if I utilize nested routes?

At the moment, I currently have these route configurations:

{ path: '/:username', component: Profile, children: [
    { path: '', component: Map , name: 'Profile'},
    { path: 'locations', component: Locations, name: 'Locations'},
    { path: 'map', component: Map, name: 'Map'}
]},

My goal is to create a markers: [] array that will be populated from my database when the mounted() lifecycle hook executes. This array will then be used in both the Map and Locations components.

I'm contemplating on the best approach to achieve this. Here are my options:

  • Include the markers: [] property along with the mounted() hook in the local state of each component, resulting in two separate axios calls in each component.
  • Add the markers: [] property and the mounted() hook to the main parent component of the nested routes, and then pass down the data as props to each component. This method only requires one axios call, but it raises concerns about passing data down through props if the nested components are not direct children of the parent element.

Considering the second scenario, I am uncertain if passing data down as props would work since the nested components may not directly be children of the parent element.

Answer №1

Indeed, the short answer is yes. If your Profile includes a router-view, you have the ability to access markers using $parent or pass them through props:

const Profile = Vue.extend({
  template: `<div>
        Profile {{ markers}}
        <!-- pass as props (used by Loaction) -->
        <router-view :markers="markers"></router-view>
    </div>`,
  data() {
    return {
      markers: []
    }
  },
  mounted() {
    // fake load
    setTimeout(() => {
      this.markers = ['A', 'B', 'C'];
    }, 1000);
  }
})
const Map = Vue.extend({
  template: `<div>
    <!-- uses $parent to get markers -->
    Map {{ $parent.markers}} 
  </div>`,
})
const Locations = Vue.extend({
  props: ['markers'],
  template: `<div>
    <!-- uses props to get markers --> 
    Locations {{ markers}} 
  </div>`,
})


const routes = [{
    path: '/',
    redirect: 'Profile'
  },
  {
    path: '/:username',
    component: Profile,
    children: [{
        path: '',
        component: Map,
        name: 'Profile'
      },
      {
        path: 'locations',
        component: Locations,
        name: 'Locations'
      },
      {
        path: 'map',
        component: Map,
        name: 'Map'
      }
    ]
  }
]
const router = new VueRouter({
  routes
});

new Vue({
  router,
  el: '#app'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.2/vue-router.js"></script>


<div id="app">
  <router-view></router-view>
  <router-link :to="{name:'Profile'}">Profile</router-link>
  <router-link :to="{name:'Map'}">Map</router-link>
  <router-link :to="{name:'Locations'}">Locations</router-link>
</div>

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

Establishing the properties of an object as it is being structured within a nested data format

I am in the process of creating a unique JSON representation, focusing on object composition to directly set key values during composition. However, I've encountered difficulty composing multiple objects in a nested manner. My goal is to find an expr ...

When the jquery loop fails to function

I need to dynamically add a class to a specific tag using jQuery depending on an if condition. Here's the code snippet: if ($(".asp:contains('Home')")) { $("ul.nav-pills a:contains('Home')"). parent().addClass('active ...

Communication between React.js and Node.js in VS Code

I recently started learning React and node js. I managed to create a simple "Hello World" project in reactjs, which works perfectly. App.js import React, { Component } from 'react'; import logo from './logo.svg'; import './App.cs ...

When the button is clicked, update the text within the <script> tags utilizing jQuery, JavaScript, or PHP

Here is the code snippet where changeme represents the text that needs to be replaced upon clicking a button: The following HTML and JavaScript code demonstrates this functionality: 1) Any input provided by the user in the field will be captured, replaci ...

Web browser local storage

Looking to store the value of an input text box in local storage when a button is submitted <html> <body action="Servlet.do" > <input type="text" name="a"/> <button type="submit"></button> </body> </html> Any sug ...

The function 'fn' is either undefined or not an object within the require-jquery.js script at Line 2813

We are experiencing a mysterious error that occurs randomly and cannot be reproduced. This error is being thrown in the following line/function in JQuery: proxy: function( fn, context ) Below is the code snippet that triggers this issue. It is related ...

Error in server file of NextJS due to Typescript issue

My current setup includes the following package versions: next v8.1.1-canary.42 @types/next v8.0.5 server.js import next from 'next'; const app = next({ dev: isDevelopment }); tsconfig.json { "compilerOptions": { "allowJs": true, ...

Setting dropdown list values with Angular

Is there a way to dynamically set the value of a drop down box on an HTML page using Angular? I am successfully getting the desired value from a REST call. Updating the values of text boxes on the page is straightforward with ng_model = myNewVal, but this ...

Excluding form items that are disabled from a request in ReactJS

In my code, I am dealing with a Form section that contains multiple Collapse.Panel sub-sections. Interestingly, the Form.Item elements within collapsed panels are not included in the form values upon submission. However, I have noticed that certain InputNu ...

Is there a way to utilize the outcome of a method in multiple sections of the HTML code?

Working with Vue.js, I have a component that cleans up some content using a method and displays the results within HTML tags: <template> .... <div v-for="(value) in mydata"> <h2>{{ prettifyMyNumber(value) }}</h2> ...

What could be the reason behind the undefined return value of val()?

When I click a button, my script is supposed to get the value of the next hidden input field. However, it always returns "undefined". What could be causing this issue and why does val() return undefined? If I only try to select the element with next(' ...

Tips on how to toggle/close a dropdown menu that is displayed on a different page using Vue

Below is a screenshot of my cart dropdown: https://i.sstatic.net/IdOZK.png The issue I am facing is that the cart stays open even when I navigate to another page. I need it to close when I move to a different page. Below is my component code: <template ...

Reveal the inner workings of functions within the Vuex Plugin

I am currently working on setting up a Vuex plugin where I want to make the undo function accessible for use in my component's click events. // plugin.js const timeTravel = store => { // .. other things function undo () { store.commit(&a ...

When configuring lint-staged, a file is created that includes a unique identifier with details on the packages that have been

When starting a new Vue project, I use npm init vue@latest and select all options (including Eslint with Prettier). For this setup, I am on Windows 11 with node v17.4 and npm v8.4. After creating the project via PowerShell, I switch to Visual Studio Code ...

basic tiptap add-on or advanced prosemirror module

Exploring the possibilities of utilizing the tiptap editor for Vue.js in conjunction with the Prosemirror editor has sparked my interest. I've delved into a lot of information about tiptap, however, I must admit that the documentation is not as compr ...

The Express.js middleware seems to be malfunctioning, as it is causing an excessive number of redirects

My Express JS middleware seems to be malfunctioning and displaying an excessive number of redirections. Even when I remove the token or log out, the browser indicates too many redirections. Middleware const isAuthenticate = async (req, res, next) => { ...

What is the best way to add an inset shadow with a transparent background in SVG?

I created a basic SVG Icon, but I'm having trouble adding an inset shadow effect to it. Is there a way to achieve this? svg { filter: drop-shadow(0.1px 1.5px 0.1px rgba(0,0,0,0.5)); } <!DOCTYPE html> <html> <body> <svg width ...

Mastering the art of effectively capturing and incorporating error data

Is there a way to retain and add information to an Error object in typescript/javascript without losing the existing details? Currently, I handle it like this: try { // code that may throw an error } catch (e) { throw new Error(`Error while process ...

Improving JavaScript Functions: Minimize duplication of helper methods

I have a set of helper functions that check for the presence of specific strings in an array and certain steps before triggering other functions. The reason for keeping them separated is because arrTours must be associated with only those arrSteps. // Help ...

Creating personalized Stop and Play controls for Swiper.js Autoplay feature in a React/Next project

My quest to create a Swiper in React with autoplay functionality using Swiper.js has been quite a challenge. Despite following the instructions diligently and researching extensively, I couldn't find a solution. I even tried referencing a jQuery examp ...