Exploring the potential of Vue with Router to create a dynamic multi-page

Struggling to come up with a suitable title for this Vue project dilemma. Here's what I'm facing:
Recently started using Router in my Vue project and feeling quite lost.

The setup in App.vue simply includes <RouterView>, which seems straightforward.

LoginView.vue serves as the entry point with a basic login popup to restrict unauthorized access, leading to HomeView.vue upon successful login.
Within HomeView.vue, I aim to showcase various content like an About page or Contact page.

Questions linger about the organization of components:
Should it be Views > LoginView.vue
Views > HomeView.vue > components > About.vue or Contact.vue
Or perhaps: Components > HomePage.vue > Views > AboutView.vue or ContactView.vue

Furthermore, I'm curious how to integrate either contact or about seamlessly into my home page without redundant content copying.

App.vue

<script setup lang="ts">
import { RouterView } from 'vue-router'

</script>

<template>
  <body>
    <div>
      <RouterView />
    </div>
  </body>
</template>

Views > LoginPage.vue

<script setup lang="ts">
import { RouterLink } from 'vue-router'
</script>

<template>
<body>
<!--Login form markup goes here-->
</body>
</template>

Views > Homepage.vue

<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
</script>

<template>
  <Body class="h-screen bg-woodsmoke-950">
   <!--Header and main content structure-->
  </Body>
</template>

Index.ts

import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'login',
      component: LoginView
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('../views/HomeView.vue')
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../components/About.vue')
    },
    {
      path: '/contact_me',
      name: 'contactMe',
      component: () => import('../components/ContactMe.vue')
    }
  ]
})

export default router

Answer №1

First and foremost, the organization of files is entirely subjective. There is no one correct way to do it. Organize your files in a way that makes sense to you.

Secondly, nesting <router-view> within another <router-view> is how you create nested routes, which seems to be what you are aiming for. The Vue Router documentation provides a detailed explanation on nested routes, so I recommend giving it a read first.

In essence, the about and contactMe routes should be placed within a `children` property under the home route. Depending on the combination of parent + child path, the <router-view> in the HomeView component will display either the About component or the ContactMe component. To make the About component display by default, leave its child route path empty.

routes: [
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/HomeView.vue')
    children: [
      {
        // The path '/' will display the 'home' component with the 'about' nested component by default
        path: '',
        name: 'about',
        component: () => import('../components/About.vue')
      },
      // The path '/contact_me' will display the 'home' component with the nested 'contactMe' component
      {
        path: 'contact_me',
        name: 'contactMe',
        component: () => import('../components/ContactMe.vue')
      }
    ]
  }
]

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

Troubleshooting: Issues with Angular2 compatibility on Safari version 9.1.2

I am encountering an issue with running my angular2 app on Safari 9.1.2. It works fine on all higher versions of Safari as well as other browsers such as Chrome, Firefox, Opera, and Edge. However, when I try to run it on Safari 9.1.2, I receive the followi ...

The lengthy email exceeds its limits

https://i.sstatic.net/juD2P.png https://i.sstatic.net/WQo8o.png Take a look at this code snippet: <div className='mt-[3vh] flex h-1/3 min-h-fit w-[80%] min-w-[300px] flex-col content-center items-center justify-center rounded-2xl bg-white shadow ...

Angular fails to include the values of request headers in its requests

Using Django REST framework for the backend, I am attempting to authenticate requests in Angular by including a token in the request headers. However, Angular does not seem to be sending any header values. Despite trying various methods to add headers to ...

When using Inertia.js with Typescript, an issue arises where the argument types {} and InertiaFormProps{} are not compatible with the parameter type Partial<VisitOptions> or undefined

I set up a brand new Laravel project and integrated Laravel Breeze along with Typescript support. After creating a form (using useForm()) and utilizing the .post() method with one of the options selected (such as onFinish: () =>), I encountered the fol ...

The distribution of intersection types is not properly handled by Typescript's array.map function

My array is of type object[] & Tree[], but when using arr.map(child => ...), the type of child is inferred as object instead of object & Tree. Is there a way to avoid this without additional casting? It's worth noting that Tree extends ob ...

Updating the status of various sections with Redux toolkit

Is it possible to update the state of a store, which consists of multiple slices, with a new state in React using Redux Toolkit? While you can revert the entire store to its initial state using extraReducers, is it also possible to change the state to som ...

Executing additional code after all tests have finished in Mocha.js

In the world of MochaJS testing, it is customary to have before and after blocks for setup and teardown operations. But what if we want to execute an extra cleanup step after all test files have been processed? This is crucial to ensure that any lingering ...

Passing props from Vue3 to a component being rendered through RouterView

I'm facing an issue with the following code snippet: <template> <router-view /> </template> <script setup lang="ts"> ... const product: Ref<IProduct|undefined>: ref(); ... </script> The challenge is ...

The JokesService (?) has encountered dependency resolution issues that Nest is unable to resolve

Currently delving into the world of NestJS and feeling a bit perplexed about the workings of "modules". In my project, I have two modules namely JokesModule and ChuckNorrisApiModule. My goal is to utilize the service provided by ChukNorrisService within th ...

Building state from multiple child components in Next.js/React: Best Practices

To better illustrate this concept, I suggest checking out this codesandbox link. This is a follow-up to my previous question on Stack Overflow, which can provide additional context. Currently, when interacting with the child elements (such as inputs), th ...

There were issues with React's compilation when integrating with antd UI

Whenever I try to compile, errors keep showing up even though I have imported from antd. I can't figure out what the problem is. These are the errors I encounter while compiling: Compiled with problems: ERROR in ./src/components/excelPage.js 130:85- ...

Ways to assign values to an array within an object

I'm attempting to transfer the contents of one array into an array within an object, but I keep encountering this error: Type 'any[]' is not assignable to type '[]'. Target allows only 0 element(s) but source may have more. Here ...

Ways to address the issue arising from the utilization of the "as" keyword

Every time I encounter this issue - why must I always provide all the details? type Document = Record<string, any> type FilteredDocument<T extends Document> = {[key in keyof T as T[key] extends (()=>void) ? never : key]: T[key]} const ...

Angular 15 experiences trouble with child components sending strings to parent components

I am facing a challenge with my child component (filters.component.ts) as I attempt to emit a string to the parent component. Previously, I successfully achieved this with another component, but Angular seems to be hesitant when implementing an *ngFor loop ...

Error in Typescript: The property 'children' is not included in the type but is necessary in the 'CommonProps' type definition

Encountering this error for the first time, so please bear with me. While working on a project, I opened a file to make a change. However, instead of actually making any changes, I simply formatted the file using Prettier. Immediately after formatting, t ...

How do I integrate a button into my grey navigation bar using tailwindcss in REACT?

Is it possible to integrate the - button into the gray bar? I am encountering an issue where my blue button extends beyond the borders of the gray bar in the image provided. export default function App() { ... return ( <div className="text-md fon ...

Exploring Cypress: Leveraging the Power of Variable Assignment

Recently, I encountered an issue while working with a variable in a Cypress each loop. Despite incrementing the variable within the loop, it resets to zero once outside of it. Can someone shed light on why this happens and suggest a solution? Thank you. p ...

Using Angular 4 to delete selected rows based on user input in typescript

I am facing a challenge with a table that contains rows and checkboxes. There is one main checkbox in the header along with multiple checkboxes for each row. I am now searching for a function that can delete rows from the table when a delete button is clic ...

Function that sets object properties based on specified keys and verifies the value

Let's consider a scenario where we have an object structured like this: interface Test{ a: number; b: string; c: boolean; } const obj:Test = { a: 1, b: '1', c: true, } We aim to create a function that can modify the value ...

Tips for parsing through extensive JSON documents containing diverse data types

In the process of developing an npm package that reads json files and validates their content against predefined json-schemas, I encountered issues when handling larger file sizes (50MB+). When attempting to parse these large files, I faced memory allocati ...