The Vue router fails to navigate to the designated destination

Having an issue with vue-router where routing doesn't work properly when trying to navigate to a child route.

  {
    path: '/user',
    name: 'User',
    component: User,
    children: [
      {
        path: 'profile',
        component: Profile,
      },
    ],
  }

Need help with programmatically routing to /user/profile

<template>
    <div>
            <button @click="goToUserProfile()">create new</button>
    </div>
</template>

<script>

export default {
  methods: {
    goToUserProfile() {
      this.$router.push('/user/profile')    // Issue with routing
       .catch(console.log);
    },
  },
};
</script>

Answer №1

Create a route named "Profile" for the path "/user/profile"

  {
    path: '/user',
    name: 'User',
    component: User,
    children: [
      {
        path: 'profile',
        name: "Profile",
        component: Profile,
      },
    ],
  }

Use the route name for navigation

this.$router.push({name: "Profile"});

Your User component should be structured like this

User.vue

<template>
<div>
    <p>This is the user component</p>
    <!-- The Profile component will replace this route-view -->
    <route-view /> 
</div>
</template>

Demo

https://codesandbox.io/s/falling-bash-6dl7m

Answer №2

Make sure to include

<router-view></router-view>
in the User Component template to properly display nested routes.

<template>
    <div>
        <button @click="goToUserProfile()">create new</button>
        <router-view></router-view>   <!-- placeholder for children routes -->
    </div> 
</template> 

Once added, you can access the nested routes using both

this.$router.push('/user/profile')
and
this.$router.push({ name: 'UserProfile' })

According to the Vue router documentation: To render components into this nested outlet, we need to use the children option in VueRouter.

https://router.vuejs.org/guide/essentials/nested-routes.html

I hope this information helps.

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

Exploring the power of JSON through recursive techniques

Greetings, I'm relatively new to the concept of recursion and it has been some time since I last worked with it, so please forgive me if my question appears a bit basic. Essentially, I have a JSON structure similar to this: { "id": "1111", "n ...

Creating a new service in Vue is a simple process that allows you to utilize powerful tools like this.$t and this.$alert

I've created a service file named message.vue <script> export default { methods:{ alert(msg,title){ this.$alertify.alert( title,msg); } } } </script> Here's how I use it: import me ...

Initiate ajaxForm submission again if necessary

Utilizing the ajaxForm function to transmit data to a PHP background process while some JavaScript functions monitor the asynchronous operation. In cases of failure, such as internet or electricity disruptions, I want users to have the ability to retry the ...

Exploring the bind() method in the latest version of jQuery,

After upgrading my JQuery version, one of the plugins I was using stopped working. Despite trying to use the migrate plugin and changing all instances of bind() to on(), I still couldn't get it to work properly. The plugin in question is jQuery Paral ...

What are the steps to include a scrollable tooltip in HTML?

Is there a way to implement a scrollable tooltip without using an iframe? Any existing jquery or css scripts that can help achieve this? If so, how can it be done? ...

Wait for AngularJS to load when the background image of a div becomes visible

Currently, I am utilizing the ng-repeat feature to fetch data from a $http.post request and then save it to the $scope.data variable. <div ng-repeat="key in [] | range:data.pages"> <div class="pageBackground" id="page_{{ (key+1) }}" ng-style= ...

Tips for refreshing the current Angular 2 Component

I'm looking for a way to refresh the same component in Angular 2. Can anyone provide guidance? Below is the code snippet I have: import { Component, OnInit, ElementRef, Renderer } from '@angular/core'; import { Router, ActivatedRoute, Para ...

Unlock the secrets of recovering deleted data from a text area in Kendo UI Angular

Currently working with Kendo UI for Angular, I need to capture deleted content and remove it from another text area within the same component. My project is using Angular-13. I'm stuck on how to accomplish this task. Any suggestions would be greatly ...

Is there a way to access the data attribute value from one component in another component without relying on an event bus mechanism?

In the 'App.vue' component, there is a data attribute called 'auth' that indicates whether the user is logged in. If it is empty, the user is not logged in; if it contains 'loggedin', then the user is authenticated. Now, let& ...

Error occurred while trying to access a file within the server using $_GET method

Struggling to access a URL within my folder, but encountering an error. I have attempted using file_get_contents without success. Warning: include(/home/vol2_3/*****/*****/htdocs/new/td.php?r=8&ids=309834): failed to open stream: No such file or direct ...

Is there a way to allow users to edit all the input fields within the td elements when they click the edit button for a specific row?

I am completely new to web dev and I'm struggling with what should be a simple task. My goal is to enable editing of all inputs in a table row when the edit link is clicked. Since I am not using jQuery, I prefer a pure JavaScript solution if possible. ...

Explore and choose JSON data for specific items depending on an array of criteria

I need to extract specific objects from a JSON file by matching them with values stored in an array. To illustrate, I have an array var list = ['test1', 'test2']; and there is a variable containing the following data: var data = [ ...

Exploring Angular 8 Route Paths

Working on an Angular 8 project, I encountered an issue with my code: src/app/helpers/auth.guard.ts import { AuthenticationService } from '@app/services'; The AuthenticationService ts file is located at: src/app/services/authentication.servic ...

Stagnant state persists despite attempted update

I am facing an issue with the useState component in my property management system. The state is not updating when loading the component. I expect the state of the item to change after receiving a response in the form stepper, but when adding a new dynamic ...

The npm install command can expose various vulnerabilities

Just starting to learn JAVASCRIPT, I ran the 'npm audit command' after encountering vulnerabilities in the npm install command. All I did was add functionality to my server/client project by incorporating HTTP requests (DELETE, POST) in Axios an ...

Node.js causing issues with retrieving data from REST Calls

I am trying to make a REST API call from my PHP and Node.js application to a specific URL provided by the client, which is expected to return a JSON object. While I am able to successfully retrieve data using PHP, I'm encountering issues with my Node ...

`I'm getting an unexpected result when using the click function`

I have been facing an issue with retrieving the updated value from a data controlled by v-model within a component. Despite observing changes in the app and Vue dev tools, whenever I try to console log the data, it consistently displays the previous value ...

Exploring the possibilities of ASP.NET paired with HTML5 web storage

I am currently working on an application and I have a feeling that utilizing html5 web storage, specifically localstorage, could greatly benefit me. However, the implementation is proving to be more challenging than anticipated. It's possible that my ...

Vue app showcasing array items through search upon button pressing

As I delve into learning Vue Js, I've encountered a bit of confusion. My goal is to showcase array elements from a Rest API based on the specific ID being searched for. For example: within my Json File are various individuals with unique IDs, and when ...

How to Use PHP to Submit Form Information

I am a beginner in PHP and I need help with sending form details to an email address. I have tried looking for solutions online but I keep running into the same issue - when I submit the form, it downloads the PHP file instead of sending an email. Below i ...