Why is my Vue application updating the route but not the router-view component?

I'm struggling to understand why the router-view in my root template of App.vue is not updating even though the route is changing correctly.

My router code navigates to /:user page and updates the view as expected. However, when I try to navigate from the MainUserView navbar to UserProfile, the route changes to /some_user/profile but the new view is not rendered.

import {createRouter, createWebHistory} from "vue-router"

import MainView from "@/views/MainView.vue";
import UserProfile from "@/views/Profile.vue";
import MainUserView from "@/views/MainUserView.vue";

const routes = [
    {
        path: "/",
        name: "home",
        component: MainView
    },
    {
        path: "/:user",
        name: "User View",
        component: MainUserView,
        children: [
            {
                path: "profile",
                name: "User profile view",
                component: UserProfile
            }
        ]
    },
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes,
});


export default router;

This is my App.vue

<template>
  <div id="wrapper">
    <MainView v-if="!user || user !== 'lukasz' && user !== 'karolina'"/>

    <navbar v-if="user"></navbar>
    <section class="section">
      <router-view/>
    </section>
  </div>

</template>

<script>
import MainView from './views/MainView.vue'
import Navbar from "@/components/Navbar.vue";

export default {
  name: 'App',
  data(){
    return {

    }
  },
  computed: {
    user() {
      return this.$store.state.user;
    }
  },
  components: {
    Navbar,
    MainView,
  },
  beforeCreate() {
    this.$store.dispatch("initializeUser");
  },
  created(){
     console.log("DUPA2")
  }
}
</script>

And here is the navbar template from which I'm trying to route to UserProfile

<template>
  <div class="wrapper">
    <nav class="navbar " :class="{'is-danger': user === 'karolina', 'is-info' : user === 'lukasz'}">
      <div class="navbar-brand">
        <router-link to="/" class="navbar-item" @click="clearUser">
          <strong>Choose again</strong>
        </router-link>
        <a class="navbar-burger" aria-label="menu" aria-expanded="false" data-target="navbar-menu">
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
        </a>
      </div>
      <div class="navbar-menu" id="navbar-menu">
        <div class="navbar-end">
          <router-link to="/send-message" class="navbar-item"
          >Send message
          </router-link
          >
          <router-link :to="{name: 'User profile view', params: {user: user}}" class="navbar-item"
          >Your Profile
          </router-link
          >
        </div>
      </div>
    </nav>
  </div>
</template>

<script>
export default {
  name: "NavbarComponent",
  props: {
  },
  methods: {
    clearUser() {
      this.$store.commit("clearUser");
    }
  },
  computed:{
    user() {
      return this.$store.state.user;
    }
  }
}
</script>

I've tried moving the navbar from App.vue to MainUserView, but it didn't help. Just displaying the router-view inside App.vue also didn't solve the issue. Therefore, I believe the problem lies elsewhere.

Any help would be greatly appreciated!

Answer №1

{
    url: "/:user",
    subpages: [
        {
            url: "",
            title: "User View",
            displayComponent: MainUserView,
        },
        {
            url: "profile",
            title: "User profile view",
            displayComponent: UserProfile
        }
    ]
}

When working with Named Routes, it's common practice to assign names to child routes.

Check out more information on nested routes here.

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

Arrange the child elements of a div to be displayed on top of one another in an HTML document

I am struggling with a div containing code .popupClass { width: 632px; height: 210px; position: absolute; bottom:0; margin-bottom: 60px; } <div class="popupClass"> <div style="margin-left: 90px; width: 184px; hei ...

Separating buttons (two buttons switching on and off simultaneously) and displaying the corresponding button based on the data

My current project involves creating a registration page for specific courses. While I am able to display the information correctly, I am facing an issue with the ng-repeat function. The problem lies in all the Register buttons toggling incorrectly. Additi ...

Step-by-step guide to aligning layout using material design in generator-gulp-angular

I am currently using generator-gulp-angular with angular-material-design and ui-router All views are loaded into index.html in the <div ui-view></div> element However, when I attempt to center the element with material design directives insid ...

Triggering a reload on the vuejs router from an external application

I'm facing a bit of a mess here, as it seems like the usual solutions for forcing a refresh in a Vue app aren't working. I have a basic page that uses some jQuery to load a third-party Vue.js app. The app loads fine and functions well. The issue ...

Can you provide guidance on transforming a JSON date format like '/Date(1388412591038)/' into a standard date format such as '12-30-2013'?

I have a json that is created on the client side and then sent to the server. However, I am facing an issue with the conversion of the StartDate and EndDate values. Can someone please assist me with this? [ { "GoalTitle": "Achievement Goal", ...

What is preventing me from utilizing global variables in distinct HTML and JavaScript files?

I am facing a perplexing issue with my HTML files, specifically index.html and lobby.html. Within main.js, which is loaded in index.html, I attempt to load lobby.html using window.location.href. Despite trying various methods to define global variables i ...

Enhanced jQuery Pop-Up Panel

A few issues to address: 1) My goal is to optimize the efficiency of this script. 2) When a user clicks on either pop-out button, it opens a window and hides the element. (Currently using .detach() to remove the embedded video player because in Firefox . ...

Localized Error: The property 'clientWidth' cannot be retrieved as the object is null or undefined

The issue with the error message seems to only occur on Internet Explorer, and unfortunately there doesn't seem to be a clear solution at the moment. Even after setting http-equiv="X-UA-Compatible" to IE8, the problem persists and I cannot seem to re ...

Tips for fixing the issue of "The use of getPreventDefault() is outdated. Please use defaultPrevented instead."

When attempting to fetch data for a specific user from an SQL Server database using JSON data, I encountered an error message in the console: "Use of getPreventDefault() is deprecated. Use defaultPrevented instead." Additionally, the values are not bei ...

Is there a way to tell if an image has completed loading?

I am facing an issue with a block of php code that randomly loads an image. My goal is to identify when the image has finished loading so I can execute additional actions on it. This is how the image is currently being loaded: // Retrieves the image $sql ...

positioning newly generated dropped elements within the DOM structure dynamically

Hello everyone, I have a query related to drag and drop functionality. I am currently working on an application that allows users to create websites using only drag and drop features. I am facing a challenge in implementing a feature where users can drop e ...

Is it possible to include a module-level controller within a directive?

I am currently navigating the complexities of controllers, modules, and services in Angular JS. In my attempt to integrate a controller into my directive, I faced an issue. The controller I intend to reference belongs to the same module as the directive, ...

Failed to convert the value "hello" to an ObjectId (string type) for the _id path in the product model

i am currently using node, express, and mongoose with a local mongodb database. all of my routes are functioning correctly except for the last one /hello, which is giving me this error: { "stringValue": "\"hello\"&qu ...

Using jQuery and JavaScript to swap images depending on the option chosen in a dropdown menu

On my existing ecommerce website, I have a dropdown menu with the following code: <select data-optgroup="10201" class="prodoption detailprodoption" onchange="updateoptimage(0,0)" name="optn0" id="optn0x0" size="1"><option value="">Please Selec ...

Exploring the shadow DOM within a Vue Component

Currently, I am working on developing a custom component using Vue3. The definition of the component looks like this: import { defineCustomElement } from 'vue'; import Panel from '~/components/panel_custom/Panel.ce.vue'; const CustomEl ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

Vue is lagging behind in implementing Virtual Dom technology

I have come across this code snippet. <template> <div ref="nodesData"> <div v-for="(item, index) in nodes" :key="index" :id="item.id"> {{ item.id }} </div> <div> ...

No results found in MongoDB query when using find method

Having an issue with an API call to my express server to retrieve employees working in the same location based on the location ID. Strangely, the API call returns an empty array while it functions correctly in the command-line interface. Definition of Emp ...

Using multiple MaterialUI components in a JavaScript page with React can pose challenges

Incorporating multiple MaterialUI Cards in my project, I encountered an issue where all the cards would expand or the select values would change simultaneously. Despite using unique key values and mapped components with distinct keys, the problem persisted ...

The concept of dynamic schema in Mongoose allows for flexibility and

Currently, I am working on creating a product schema that involves setting pricing in different currencies. However, I am facing confusion regarding how to dynamically create currency options. The pricing may vary in one currency or multiple currencies as ...