Displaying parent component when URL changes in Vue Router for child components

Currently, I am delving into the world of Vue and encountering an issue with nested routers. Despite defining some child routers in the routes, whenever I access the child route, the parent component continues to be displayed. Below is the snippet of my code:

App.vue:

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-link :to="{name: 'Home'}">Home</router-link>
    <router-link to="/cart">Cart</router-link>
    <router-link to="/admin">Admin</router-link>
    <router-link to="/admin/add">【Admin Add】</router-link>
    <router-link to="/admin/edit">Admin Edit</router-link>

    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'app'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Router/index.js:

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/pages/Home'
import Cart from '@/components/pages/Cart'
import Index from '@/components/pages/Admin/Index'
import Add from '@/components/pages/Admin/Add'
import Edit from '@/components/pages/Edit'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/cart',
      name: 'Cart',
      component: Cart
    },
    // {
    //   path: '/admin/index',
    //   name: 'Index',
    //   component: Index
    // },
    // {
    //   path: '/admin/add',
    //   name: 'Add',
    //   component: Add
    // },
    // {
    //   path: '/admin/edit',
    //   name: 'Edit',
    //   component: Edit
    // }
    {
      path: '/admin',
      // name: 'Admin',
      component: Index,

      children: [
        {
          path: 'add',
          name: 'Add',
          component: Add
        },
        {
          path: 'edit',
          name: 'Edit',
          component: Edit
        }
      ]
    }
  ]
})

When I opt to exclude the children routers, the component displays correctly, similar to the commented-out code above.

I find myself in a state of confusion regarding this matter and would greatly appreciate any assistance provided.

Answer №1

Make sure to include

<router-view></router-view>
in your Index component to enable routing. Here's a helpful example from the vue-router documentation.

const User = {
  template: `
    <div class="user">
      <h2>User {{ $route.params.id }}</h2>
      <router-view></router-view>
    </div>
  `
}

const UserHome = { template: '<div>Home</div>' }
const UserProfile = { template: '<div>Profile</div>' }
const UserPosts = { template: '<div>Posts</div>' }

const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User,
      children: [
        // UserHome will be rendered inside User's <router-view>
        // when /user/:id is matched
        { path: '', component: UserHome },

        // UserProfile will be rendered inside User's <router-view>
        // when /user/:id/profile is matched
        { path: 'profile', component: UserProfile },

        // UserPosts will be rendered inside User's <router-view>
        // when /user/:id/posts is matched
        { path: 'posts', component: UserPosts }
      ]
    }
  ]
})

const app = new Vue({ router }).$mount('#app')
<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">
  <p>
    <router-link to="/user/foo">/user/foo</router-link>
    <router-link to="/user/foo/profile">/user/foo/profile</router-link>
    <router-link to="/user/foo/posts">/user/foo/posts</router-link>
  </p>
  <router-view></router-view>
</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

What is the mechanism behind pushing an empty array into another empty array?

let arr = []; console.log(arr.push([])); // 1 Instead of logging [[]], the output is 1. Can someone explain what is happening in the code above? ...

Merge multiple Javascript files into one consolidated file

Organizing Files. /app /components /core /extensions - array.js - string.js /services - logger.js /lib - core.js Core.js (function() { 'use strict'; an ...

I am selecting specific items from a list to display only 4 on my webpage

I am trying to display items from a list but I only want to show 4 out of the 5 available items. Additionally, whenever a new item is added, I want it to appear first on the list, with the older items following behind while excluding the fifth item. Despi ...

Steps for eliminating an element upon the second click:

I am faced with a challenge where I need to dynamically add elements to a container on the first click and delete them on the second click. I feel like I am complicating things unnecessarily and there must be a simpler and more elegant solution available. ...

Prevent the opening of tabs in selenium using Node.js

Currently, I am using the selenium webdriver for node.js and loading an extension. The loading of the extension goes smoothly; however, when I run my project, it directs to the desired page but immediately the extension opens a new tab with a message (Than ...

Removing a CSS class using JQuery

Within my website layout, I have a div that is dynamically included using PHP. This div is inserted in two different locations, each inside its own parent div. <div id="parent_div"> <div id="contact_details_div" class="contact_details_div sam ...

Is it recommended to use new Vue() on each Blade or components?

Currently, I am diving into learning Vue.js and Laravel. As far as I know, a fresh Vue application is typically created in the app.js file by default: const app = new Vue({ el: '#app', }); Up to this point, my process has involved creating ...

Retrieve information from an API and populate a MDBootstrap datatable using Vue.js and Axios

I am looking to populate a mdbootstrap datatable with data from my API. Is there a way for me to create a method that can call the getPosts() API and then write the results into the rows[] array? <template> <mdb-datatable :data="dat ...

The occurrence of the "contextmenu" event can cause disruption to the execution of a function triggered by the "onmousemove" event

Currently in the process of developing a Vue application utilizing a Pinia store system. Within my BoxView.vue component, I have created a grid layout with draggable elements that have flip functionality implemented within the BoxItem.vue component. Spec ...

Pausing a running function in React

Exploring Visual Sorting Algorithms In the process of creating a visual sorting algorithms tool for educational purposes, I have developed a function called sortArray() that handles the animation of the sorting process on arrays. The functionality is evid ...

Extract information from a webpage using JavaScript through the R programming language

Having just started learning about web scraping in R, I've encountered an issue with websites that utilize javascript. My attempt to scrape data from a specific webpage has been unsuccessful due to the presence of javascript links blocking access to t ...

There seems to be a glitch in my programming that is preventing it

Can someone please help me troubleshoot this code? I'm unable to figure out what's going wrong. The concept is to take user input, assign it to a variable, and then display a string. However, nothing appears on the screen after entering a name. ...

Ensure that a string contains only one instance of a specific substring

I need a function that removes all instances of a specific substring from a string, except for the first one. For example: function keepFirst(str, substr) { ... } keepFirst("This $ is some text $.", "$"); The expected result should be: This $ is some tex ...

Having trouble adding flexslider before a div element with jQuery

Hey there! I recently got flexslider from woothemes.com. The page structure I'm working with looks something like this: <div class="parentdiv anotherdiv"> <div class="child-div1">some buttons here</div> <div class="child-div2"& ...

IE and Firefox display different responses when encountering an empty XML document

When working with jQuery to read an XML file, I occasionally encounter the situation where the XML is empty. In this case, I anticipate that the error function (no_info) will be triggered because the file is not formatted as expected for the dataType. Int ...

What are some creative ways to utilize postMessage instead of relying on nextTick or setTimeout with a zero millisecond delay?

I just came across a theory that postMessage in Google Chrome is similar to nextTick. This idea somewhat confused me because I was under the impression that postMessage was primarily used for communication between web workers. Experimenting with expressio ...

What is the best method in typescript to combine objects in an array with identical properties but varying values?

interface IData{ cabinTo:string[]; cabinFrom:string; } const dataAfterIteration= [{cabinTo:"A",cabinFrom:"B"}, {cabinTo:"A",cabinFrom:"C"}, {cabinTo:"B",cabinFrom:"C"}, { ...

Is it possible to wait for two asynchronous actions using only one await statement?

I have a situation where I am dealing with a node module that exports a promise to resolve a database connection. Once this connection is resolved, I then need to use it to query records which involves another asynchronous operation. Is it possible to hand ...

When the "x" close icon is clicked, the arrow should toggle back to 0 degrees

I've been tackling the challenge of creating an accordion and I'm almost there. However, I'm facing an issue where the arrow doesn't return to its original position after clicking the close "x" icon. The toggle works fine but the arrow ...

Comparing Angular extend to $provide.decorator: A breakdown

I find myself in a state of confusion. Can you please provide some clarity on the distinction between angular.extend() and $provide.decorator? When and why would one use the latter option? Does decorator serve a different purpose compared to extend? Desp ...