The children routes in my Vue application are failing to render their content once resolved, instead opting to render the parent view

I've gone through the entire process again, cleaning up the code a bit (I'm still learning Vue so my code might be a bit messy) but I can't seem to get the component for the child path to render. It always defaults to the parent path.

This is the code in my products.js file (all paths under products)

import Products from '../views/Products.vue'
import Product from '../views/Product.vue'

export default {
  path: '/products',
  name: 'Products',
  component: Products,
  children: [
    {
      path: ':id',
      name: 'OneProduct',
      component: Product
    }
  ]
}

This is the code in my product view (the view for the path: /products/:id)

<template>
  <div>
    <ExpandedProduct
      :productName="$route.query.productName"
      :price="$route.query.prodPrice"
      :description="$route.query.description"
      />
  </div>
</template>

<script>
import ExpandedProduct from '../components/ExpandedProduct'

export default {
  name: 'Product',
  components: {
    ExpandedProduct
  }
}
</script>

<style lang="scss" scoped>

</style>

The ExpandedProduct component is supposed to be rendered when the route resolves to '/products/:id' This is the code in ExpandedProduct.vue

<template>
  <div>
    <div class="carousel-holder">
      <v-carousel>
        <v-carousel-item
          v-for="(item,i) in items"
          :key="i"
          :src="item.src"
          reverse-transition="fade-transition"
          transition="fade-transition"
        ></v-carousel-item>
      </v-carousel>
    </div>
    <div class="description-holder">
      <h2>{{ $route.query }}</h2>
      <h4>{{ $route.query.prodPrice }}</h4>
      <h3>{{ $route.query.description }}</h3>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ExpandedProduct',
  props: {
    productName: {
      type: String,
      required: true,
      default: 'N/A'
    },
    price: {
      type: String,
      required: true,
      default: 'N/A'
    },
    description: {
      type: String,
      required: true,
      default: 'N/A'
    }
  },
  data () {
    return {
      items: [
        { src: 'https://cdn.vuetifyjs.com/images/carousel/squirrel.jpg' },
        { src: 'https://cdn.vuetifyjs.com/images/carousel/sky.jpg' },
        { src: 'https://cdn.vuetifyjs.com/images/carousel/bird.jpg' },
        { src: 'https://cdn.vuetifyjs.com/images/carousel/planet.jpg' }
      ]
    }
  }
}
</script>

<style lang="scss" scoped>

</style>

If anyone can help me understand what I might be overlooking

Answer №1

Developing a /product pathway alongside a distinct /product/:id pathway differs from incorporating children with :id to a primary /product route.

The former establishes a webpage without the :id parameter and another page that manages the :id parameter. The latter forms a SINGLE page where a child router-view acquires the :id parameter.

I find it clearer with code examples:

1. Here is the /product + /product/:id

const Foo = {
  template: `
    <div>Foo</div>
  `
}

const FooId = {
  template: `
    <div>Foo+{{ $route.params.id }}</div>
  `
}

const Bar = {
  template: `
    <div>Bar</div>
  `
}

const Baz = {
  template: `
    <div>Baz</div>
  `
}

const routes = [{
    path: '/foo',
    component: Foo
  },
  {
    path: '/foo/:id',
    component: FooId
  },
  {
    path: '/bar',
    component: Bar
  },
  {
    path: '/baz',
    component: Baz
  }
]

const router = new VueRouter({
  routes
})

new Vue({
  router,
  el: "#app",
})
div {
  border: 1px solid black;
  background: rgba(0, 0, 0, 0.2);
  padding: 8px 16px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
  <h3>APP</h3>
  <p>
    <router-link to="/foo">Go to Foo</router-link><br />
    <router-link to="/foo/1">Go to Foo-1</router-link><br />
    <router-link to="/foo/2">Go to Foo-2</router-link><br />
    <router-link to="/bar">Go to Bar</router-link><br />
    <router-link to="/baz">Go to Baz</router-link><br />
  </p>
  <h3>ROUTES:</h3>
  <router-view></router-view>
</div>

2. This is the /product root + child :id elements

const Foo = {
  template: `
    <div>
      Foo
      <router-view></router-view>
    </div>
  `
}

const FooId = {
  template: `
    <div>Foo+{{ $route.params.id }}</div>
  `
}

const Bar = {
  template: `
    <div>Bar</div>
  `
}

const Baz = {
  template: `
    <div>Baz</div>
  `
}

const routes = [{
    path: '/foo',
    component: Foo,
    children: [{
      path: ':id',
      component: FooId
    }]
  },
  {
    path: '/bar',
    component: Bar
  },
  {
    path: '/baz',
    component: Baz
  }
]

const router = new VueRouter({
  routes
})

new Vue({
  router,
  el: "#app",
})
div {
  border: 1px solid black;
  background: rgba(0, 0, 0, 0.2);
  padding: 8px 16px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
  <h3>APP</h3>
  <p>
    <router-link to="/foo">Go to Foo</router-link><br />
    <router-link to="/foo/1">Go to Foo-1</router-link><br />
    <router-link to="/foo/2">Go to Foo-2</router-link><br />
    <router-link to="/bar"> Go to Bar </router-link> <br/>
    <router-link to="/baz"> Go to Baz </router-link> <br/>
  </p>
  <h3> ROUTES: </h3>
  <router-view> </router-view>
</div> 

3. Contrast

Alternatively called children paths signify nested paths. This implies treating a route as the base while containing an additional router-view inside (for illustrative purposes only). (Nested routes)


Therefore, the essential query is: do you desire distinct pages for your products and each individual product (v1 - two separate routes), or opt for a central page encompassing all products while governing the subsection for each product therein (v2 - nested routes).

EDIT

Included some CSS styling for enhanced clarity regarding the hierarchical structure.

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

Tips for Printing a div Element with Horizontal Scrollbars

My webpage has both vertical and horizontal scroll bars, but when I use window.print(), it only prints the visible content in the window. Is there a way to print the entire scrollable content within the window? ...

What is the appropriate placement for setting Firebase auth state persistence in a Vue.js application?

Welcome Currently working on a web application using Quasar/Vue.js and Firebase that requires user authentication. My Objective I am aiming to implement a common feature - keeping users logged in even after they have closed the browser or tab. Potentia ...

Using jSLint in combination with Angular leads to an unexpected error regarding the variable "$scope"

When performing a jSLint check on my Angular-based app, I encountered an "Unexpected '$scope'" error. To replicate the issue, you can try inputting the code snippet below into jslint.com. I'm puzzled as to why the first function declaration ...

Effortlessly eliminate query strings from a URL in a Vue SPA application

Imagine you have a Vue2 application at http://www.example.com, with two routes ('/', '/dashboard'). When someone accesses '/', they are automatically redirected to '/dashboard'. Now, another single sign-on (SSO) s ...

Tips on using JQuery to extract form field information from a drop-down menu, display it in a div, and then compare it with the subsequently

In my HTML file, I am using two dropdown lists and JQuery for validation. First, I need to save the selected items from both dropdown lists in a variable and then compare them with the next selection. If the data from both dropdown lists match, an alert m ...

A guide on populating a dropdown menu with spring and hibernate in JSP

I'm a newcomer here and seeking ideas from you all. I have 4 dropdown lists and want to populate one select box based on the selection made in another select box using database values. I have already set up the database, but unsure how to proceed. Any ...

Pair of dimensions painting with d3 version 4

I am having trouble converting my code from d3 v3 to d3 v4 Below is the original code snippet: var brush = d3.svg.brush() .x(x) .y(y) .on("brushstart", brushstart) .on("brush", brushmove) .on("brushend", brushend); However ...

Utilizing the power of Scoped CSS with Bootstrap/Bootstrap-Vue Integration

I'm currently working on a chrome extension and utilizing Bootstrap-Vue in my Vue files. I have imported bootstrap/bootstrap-vue into my js file, but the styling is being applied globally. Is there a way to scope the Bootstrap only onto specific inser ...

Exploring the functionality of a Vue component designed solely through a template

I currently have a basic Vue application set up: <!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'& ...

Implementing updates to a website from a database without the need for a page refresh

I am eager to delve into the world of AJAX and have identified a seemingly straightforward challenge that I believe will serve as an informative learning experience. Imagine a scenario where users are continuously adding new entries to a database table. ...

Event listener in JavaScript for Bootstrap 5 modal

Currently, I am utilizing Bootstrap v5.1.3 along with vanilla JavaScript, but it appears that I have misunderstood how to set up modal event listeners. Below is my current setup for two modals: var firstModal = new bootstrap.Modal(document.getElementById(& ...

How can I asynchronously parse JSON data from a URL on a Windows phone and display it in a

As an Android developer exploring the world of Windows Phone for the first time, I came across this resource on how to handle list boxes in Windows Phone 7/8. However, my challenge now is parsing JSON from a URL instead of XML as shown in the example. Whil ...

Guide to dividing a string and structuring it into an array

I need help breaking apart these strings: var str = '(john) the quick brown (emily) fox jumps over (steam) the lazy dog.' var str1 = '(john) the quick brown fox jumps over (steam) the lazy dog.' to create an array like this: joh ...

Navigate through set of Mongoose information

I have a challenge where I need to retrieve an array of data from Mongoose, iterate through the array, and add an object to my Three.js scene for each item in the array. However, when I try to render the scene in the browser, I encounter an error that say ...

Text transitions in a gentle fade effect, appearing and disappearing with each change

I want to create a smooth fade in and out effect for the text within a div when it changes or hides. After researching on Google and Stack Overflow, I found that most solutions involve adding a 'hide' CSS class and toggling it with a custom func ...

Simulating a function while testing a different function within a Vue composable

In my scenario, there is a case that involves the following: A composable function named useTreeData(), which incorporates several other functions A function called onNodeChange() which is returned as a result of destructuring the useTreeData Other functi ...

npm: Import a package from a GitHub repository that does not belong to me

I have encountered a package that I need for my project, but it is not available in npm. I am considering the option of uploading the package to npm myself. However, I am unsure if this is ethically or legally acceptable. What is your opinion on this mat ...

One should refrain from loading the API in Angular when there is no data present, by utilizing the global.getData method

Check out this code snippet: loadNextBatch() { console.log('scrolldown'); this.pageIndex = this.pageIndex + 1; this.global.getData(`/conditions/latest?start=${this.pageIndex}&length=${this.pageSize}`) .pipe(take(1)).subscr ...

How do I pass a localhost database URL to my server.js file using module.exports in Node.js with MongoDB?

I am encountering an issue connecting to a database using mongoose on my localhost. Within my server.js file, I have the following code: var express = require('express'); var app = express(); //Creating our ap ...

What steps can be taken to properly display dateTime values in a data table when working with JavaScript (VueJS) and PHP (Laravel)?

I am facing an issue where I am unable to save user inputted date-time values from a modal into a data table. Despite receiving a success message, the dateTime values are not being added to the table. My payload only displays the state and approval fields ...