Display various components depending on the route in VueJS

My current setup looks like this:

App.vue

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

This serves as my default page, and I want it to load two different layouts for admin and public. Everything works well except for a small issue with the public layout. I want to have a shared NAVBAR and FOOTER in all public components/pages without duplicating them in every component.

routes.js

import ...
export const routes = [
// public
  { path: "",
    name: 'main',
    component: Main},
  { path: "/about",
    name: 'about',
    component: About},

// private
  { path: "/login",
    name: 'login',
    component: AdminLogin},
  { path: "/admin",
    name: 'admin',
    component: AdminHome}
]

The default route is MAIN where the "common public" components (navbar and footer) are found.

Main.vue

<template lang="html">
  <div class="">
    <app-navbar></app-navbar>
    <div style="margin-top: 64px">

      <home></home>

      <div class="container">
        <app-footer></app-footer>
      </div>
    </div>
  </div>
</template>

<script>
  import Home from './Home.vue'
  import Navbar from './shared/Navbar.vue'
  import Footer from './shared/Footer.vue'

  export default {
    components: {
      Home,
      'app-navbar': Navbar,
      'app-footer': Footer
    }
  }
</script>

I want to only change the content in the "middle" based on the selected route. Currently, the default is <home>. How can I dynamically change it based on the routes? I don't want the same structure -> navbar, content, footer in all pages because it would be redundant. Is there a better approach to handle this?

Can I implement something like this in Main.vue:

navbar

case 
 when route == 'about' then import(about)
 else import(home)
end

footer

What would be the best approach to achieve this?

Answer №1

If you're looking for a simple solution to address this issue, consider using the meta property in your router setup. For instance, modify your login route as follows:

{
    path: "/login",
    name: 'login',
    meta: {
        NoNavbar: true,
        NoFooter: true
    },
    component: AdminLogin,
},

Then, in Main.vue, you can dynamically render components based on these conditions:

<template v-if="!this.$router.resolve(this.$route.path).route.meta.NoNavbar">
    <app-navbar></app-navbar>
</template>

Similarly, for the footer:

<template v-if="!this.$router.resolve(this.$route.path).route.meta.NoFooter">
    <app-footer></app-footer>
</template>

Important Note

I have not personally tested this approach but it should provide some insight :)


Below is an example of how you could create a component that functions as a layout for your application:

<div id="app">
    <template v-if="!this.$router.resolve(this.$route.path).route.meta.NoNavbar">
        <app-navbar></app-navbar>
    </template>

    <main>
        <router-view></router-view>
    </main>

    <template v-if="!this.$router.resolve(this.$route.path).route.meta.NoFooter">
        <app-footer></app-footer>
    </template>
</div>

This way, you apply the layout based on the current route first, and then only the main component(s) will be rendered within the <main> tag.

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

Adding fewer components to your current Angular 5 project

I have a JS Fiddle showcasing a CSS chart. How can I integrate LESS into my current Angular 5 project to make use of this chart? Also, where should I place the JavaScript and references to the LESS file from this example within my Angular component? The li ...

Error message indicating that the function is not defined within a custom class method

I successfully transformed an array of type A into an object with instances of the Person class. However, I'm facing an issue where I can't invoke methods of the Person class using the transformed array. Despite all console.log checks showing tha ...

Conceal the form after it has been submitted

I am working with the following JavaScript function: var form = $('#review-contact-form'); form.submit(function(event){ event.preventDefault(); var form_status = $('<div class="form_status center"></div>'); $.aj ...

PHP AJAX Request Failing to Transfer Files

I am having trouble with sending files in a PHP AJAX Request: Here is the form code: <form class="frmContact" action="#" method="post"> <div class="col-md-6"> <input type="hidden" name="emailTo" id= ...

By changing the name of my file to .js.erb, I am able to seamlessly incorporate erb syntax within my javascript code, but this

Currently, I am using chessboard-0.3.0.js in a rails application. Due to the rails asset pipeline setup, I've had to make adjustments to the js code specifically related to rendering images, such as Pieces. In line 445 of chessboard.js, it states: c ...

Hide a dropdown menu if a user clicks on any item within it

Currently, I am developing a Notification feature for my app similar to the notifications on Facebook. The dropdown opens when I click a button in the header navigation, displaying the notification list with a Link (from react-router) included. The main r ...

When trying to access localhost:5000, the index.js file is unable to retrieve /

const NutritionAPI = require('./nutritionapi'); const nutService = new NutritionAPI('50cee42503b74b4693e3dc6fccff8725','2755697297a84ac5a702461b166e71f6'); // Setting up Express webhook const express = require('express&ap ...

Changing $scope does not automatically refresh the selected option when using ng-options with <select> in AngularJS

My select element is structured like this: <select ng-model="exportParam" ng-options="item as item.lib for item in allExportParams | orderBy:'lib'" class="form-control"> </select> To save its state for later display, I sto ...

Issue with factory function failing to return any data

I am using an angularjs factory to retrieve data with the $http.get() method: 'use strict'; app.factory('apiService', ['$http', function ($http) { var apiService = {}; apiService.urlBase = 'http://localhost:1337/ ...

Utilizing Chosen JS along with the clone(true,true) method for re-rendering upon appending

I am currently utilizing the Chosen JS jQuery plugin and attempting to make it re-render every time a cloned element, with all its event listeners copied over, is added to the document. Below is my code snippet: var container = jQuery(self.options.parent ...

Using the jQuery dialog to load a URL with a datetime picker integrated into

I recently created two pages. One page contains a link that opens a dialog and loads another page inside that dialog. However, when I click on the calendar on the loaded page, I receive the error message: "Cannot read property 'inline' of undefin ...

Using Vue to bind data without the colon syntax or shorthand specification

Is there a method in Vue to avoid using shorthand or colon? I'm experiencing difficulties implementing it with React-Dom for server rendering in Node.js. https://i.stack.imgur.com/RHJXK.png ...

What could be the reason for the malfunctioning of the where feature in Cloud Firestore?

Looking to create a warning system using discord.js and utilizing Cloud Firestore as the database. The goal is to have a system where when an admin triggers a command, it utilizes the where function to locate all documents containing the userid of the user ...

Add CSS styles directly into the shadow-root instead of the head tag | Vue.js and Webpack

Currently, I'm developing a widget that can be embedded on websites using Vue.js along with vue-custom-element. Everything was going well until I encountered an issue. The problem arises when trying to integrate a component (along with its CSS) from ...

Using Redux and Typescript with functional components: the imported component depends on props provided by Redux

I'm currently working on a component that has the following structure: It features an interface with a "alerts" property It's connected to Redux and receives the "alerts" from props ...

React-modal triggers the file-explorer upon exiting the dropzone

Within my project, I have implemented a button that triggers a modal to appear on mouse-over. This button is nested inside a dropzone element. https://i.sstatic.net/95dxy.png The issue arises when I exit the modal by clicking (not exiting with the escape ...

Struggling with the nodejs peepcode tutorial - need some help getting it to run

After purchasing and following the latest nodejs peepcode tutorial, I have hit a roadblock at the initial step. I have spent hours trying to debug my code, but tracing errors in nodejs seems like solving a riddle to me. My app structure is as follows: e ...

I am looking to incorporate an 'x' button to enable the closure of a material popper interface

Creating a Material UI Popper with a close button (x), but the functionality is not working as expected. Each popper has its own unique class. The issue lies in the const handleClose that is supposed to close the popper when clicked, but currently, nothin ...

How can I access a store getter in Vue after a dispatch action has finished?

I am currently utilizing Laravel 5.7 in combination with Vue2 and Vuex. While working on my project, I have encountered an issue where Vue is not returning a store value after the dispatch call completes. The workflow of my application is as follows: Wh ...

Transferring PHP data to JQuery through HTML elements

When adding a new comment to the list using PHP variables containing HTML code, the method of choice is typically through JQuery. The question arises - what is the most effective way to achieve this? Would one generally opt for an ajax call? Here's t ...