Display the default child of vue-router 4

Need Assistance with Rendering Default Child View in Vue

I am currently facing an issue with rendering the default child view for the Category view. I have come across a similar problem discussed on Stack Overflow, but it seems to be related to VUE2 and older versions of vue-router. When navigating to

<router-link :to="{ name: routeName, params: { category: item.id } }
, everything displays correctly except for <router-view />, which remains empty...

I have tried using beforeUpdate() and beforeCreate() as a workaround, but it feels like I am overcomplicating things. If I visit /category/{id}, then move to /category/{id}/room/{id} and return one page back, the default view gets rendered.

Is there a way to ensure that the default child loads when navigating to /category/{id}?

router.js

{
  path: '/category/:category',
  name: 'Category',
  props: true,
  component: Category,
  children: [
    {
      path: '',
      name: 'FavouriteDevicesInCategory',
      component: Devices,
      props: true,
    },
    {
      path: 'room/:room',
      name: 'Devices',
      component: Devices,
      props: true,
    },
  ],
},

Category.vue - view

<template>
  <div class="control">
    <div class="left">
      [...]
    </div>
    <div class="right">
      <router-view />
    </div>
  </div>
</template>

<script>
export default {
  props: ['category', 'room'],
  /** generate default router-view */
  beforeUpdate() {
    this.$router.push('');
  },
  beforeCreate() {
    this.$router.push('');
  },
};

Answer №1

If your main component is set to Category, the route structure should be created as follows:

{
  path: '/category',
  name: 'Category',
  props: true,
  component: Category,
  children: [
    {
      path: '/:categoryId',
      name: 'FavouriteDevicesInCategory',
      component: Devices,
      props: true,
    },
    {
      path: 'room/:roomId',
      name: 'Devices',
      component: Devices,
      props: true,
    },
  ],
},

When no specific id is added to the URL, the default rendering will be the Category component. However, when an id is included in the URL, the navigation will be directed to the Devices component.

Answer №2

After some careful consideration, I believe I have come up with a solution that may appear a bit messy, but it appears to be the most effective answer to this particular issue.

{
  path: '/category/:category',
  // name: 'Category',
  props: true,
  component: Category,
  children: [
    {
      path: '',
      name: 'Category',
      component: Devices,
      props: true,
    },
    {
      path: 'room/:room',
      name: 'Devices',
      component: Devices,
      props: true,
    },
  ],
},

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 refreshing HTML multiple file upload without reloading the page

I am currently working on a feature that involves counting the number of files uploaded. If more than 10 images are uploaded, I want to clear the input field while keeping everything else in the form intact. Everything was working fine until I encountered ...

Submitting a PDF document to the server with PHP Laravel through AJAX

Struggling to send a PDF file via AJAX to my server for handling by a PHP script in a Laravel project. The file doesn't seem to be making it to the server. Despite receiving a 200 response in the network, the server is returning 'file not presen ...

An error is thrown when using AngularJS .length property

Currently, I am carrying out a regular task within my Filter to verify if angular.module('someApp') .filter('filterSomeData',['$filter',function ($filter) { return function (items, keyObj) { var filterObj ...

Encountered an error while attempting to load resource in Node.js

I'm currently working on a project utilizing Node js (Express...). Let me do my best to explain the issue I am encountering. My work is being done on localhost, and the main page of my index.html has buttons that lead to other pages when clicked. I c ...

PlateJS: Transforming HTML into data

Trying to implement a functionality where clicking on a button retrieves an HTML string. The objective is to have this rich text editor within React-Hook-Form, and upon form submission, the value will be saved as HTML for database storage. Below is the pr ...

The JavaScript array slideshow is experiencing some glitches in its transition

After diving into JavaScript recently, I managed to center a div and make it fullscreen as the window resizes. However, things got tricky when I added a script I found online to create an image transition using an array. Unfortunately, these scripts are co ...

What could be causing the Vue.js image component to malfunction?

I am having an issue. I want to create a Vue.js Component. This component displays an image, similar to the <img> tag. If you are familiar with the <img> tag, this question should be easy for you to understand. Here is the code I have: props ...

The function type '(state: State, action: AuthActionsUnion) => State' cannot be assigned to the argument

I have encountered a persistent error in my main.module.ts. The code snippet triggering the error is as follows: @NgModule({ declarations: [ PressComponent, LegalComponent, InviteComponent ], providers: [ AuthService ], imports: ...

Is there a way to verify if a React hook can be executed without triggering any console errors?

Is there a way to verify if a React hook can be invoked without generating errors in the console? For example, if I attempt: useEffect(() => { try { useState(); } catch {} }) I still receive this error message: Warning: Do not call Hooks i ...

What could have caused my javascript file to disappear from npm?

After creating a small library consisting of a .js file with commonly used functions, I placed it in the node_modules directory alongside my other packages. Everything seemed to be going well. A few days later, I decided to add a new package using npm ins ...

What purpose does the symbol '$' serve in React component properties?

While delving into the world of styled-component, I encountered some difficulties with the 'adapting based on props' aspect. import './App.css'; import styled from 'styled-components' const PrimaryButton = styled.button` co ...

What is the method to establish a reference based on a value in programming?

Having some trouble setting the 'ref' of a TextInput from a value. Here's an example: var testtest = 'testvalue' <TextInput ref=testtest autoCapitalize="none" autoCorrect={false} autoFocus={false} placeholderTextColor="#b8b8b ...

Display a vibrant welcome screen on an Android WebView that ensures a visually appealing experience while the content loads for the

When launching an application, the desired behavior is as follows: Display a splash screen while simultaneously loading a URL Upon the firing of a JavaScript interface event on page load, remove the splash screen Mainactivity.java myWebView.addJavascript ...

Preventing page re-rendering with redux when a condition is not met

I am currently working on a page that features a question paper with multiple options and a button to navigate to the next question. import Grid from "@material-ui/core/Grid"; import Typography from "@material-ui/core/Typography"; import React, { useEffec ...

The close menu button is not functioning properly when clicked outside the menu - the buttonevent.matches is not recognized as a

I am encountering an issue with the dropdown menu that is not closing when clicking outside of the menu button. Despite having faced this problem before, I can't seem to find a solution now. Any help would be greatly appreciated as I am uncertain why ...

Utilizing chrome.scripting to inject scripts in TypeScript

I am currently facing an issue wherein I am attempting to integrate chrome extension JavaScript code with TypeScript: const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); let result; try { [{ result }] = await c ...

The method of inserting a JSON dates object to deactivate specific days

I am currently utilizing a date picker component that can be found at the following link: While attempting to use the disabledDays section below, I have encountered an issue where I am unable to apply all three options. The blockedDatesData option works o ...

What is the best way to pass the "$user" variable in a loadable file using ajax?

Is there a way to send the variable user to the mLoad.php file before executing this script? Any suggestions would be greatly appreciated. Thank you! $(document).ready(function(){ $("#message_area").load('mLoad.php'); $("#userArea").submit(func ...

Custom JSON filtering

I have a JSON object called Menu which contains various menu items for my system that I am developing using VueJS + Vuetify. I need to filter these menu items based on the "text" field, regardless of position in the text and without differentiating between ...

Implementing a blur effect on a CSS loader

I have successfully implemented a loader feature where a loading animation is displayed upon clicking the submit button, indicating that the form submission is in progress. However, I am encountering an issue when trying to apply a blur effect to the entir ...