Utilizing Vue.js: Dynamically Rendering Components Based on Routes

I needed to hide some components for specific Routes, and I was able to achieve this by using a watcher for route changes that I found in this StackOverflow question - Vuejs: Event on route change. My goal was to not display the header and sidebar on the customizePage (route - /customize). However, I encountered an issue when doing a hard reload from that page as the watch did not execute, causing it to fail. To solve this problem, I added the functionality to mounted() so that it also runs on reload.

However, having the same function in both mounted and watcher seems odd. Is there a better way to handle this?

<template>
    <div>
        <TrialBanner v-if="$store.state.website.is_trial"/>
        <div class="page-body-wrapper" :class="{ 'p-0' : isCustomizePage}">
            <Sidebar :key="$store.state.user.is_admin" v-if="!isCustomizePage"/>
            <div class="main-panel" :class="{ 'm-0 w-100' : isCustomizePage}">
                <Header v-if="!isCustomizePage"/>
                <div class="content-wrapper" :class="{ 'p-0' : isCustomizePage}">
                    <router-view :key="$store.state.websiteId"></router-view>
                </div>
            </div>
        </div>
    </div>
</template>


mounted() {
  if(this.$route.path == '/customize') {
     this.isCustomizePage = true;
  } else {
     this.isCustomizePage = false;
  }
},
watch: {
  $route (to, from){
     if(this.$route.path == '/customize') {
       this.isCustomizePage = true;
     } else {
       this.isCustomizePage = false;
     }
  }
}

Answer №1

Simple solution: Implement an immediate watcher

watch: {
  $route: {
     immediate: true,
     handler(to, from) {
         if(this.$route.path == '/customize') {
           this.isCustomizePage = true;
         } else {
            this.isCustomizePage = false;
         }
     }
  }
}

Complex yet flexible solution: Utilize "layout" components.

Check out the demo here

The concept involves creating "Layout" components, using the meta tag on routes to define layouts for each route, and then employing a dynamic component in App.vue to specify which layout to use.

App.vue

<template>
  <div id="app">    
    <component :is="layout">
      <router-view></router-view>
    </component>
  </div>
</template>

<script>

export default {
  name: "App",
  computed: {
    layout() {
      return this.$route.meta.layout || 'default-layout';
    }
  }
};
</script>

Default layout component

<template>
    <div>
        <TrialBanner v-if="$store.state.website.is_trial"/>
        <div class="page-body-wrapper" >
            <Sidebar :key="$store.state.user.is_admin" />
            <div class="main-panel">
                <Header />
                <div class="content-wrapper">
                    <slot></slot>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
export default {
  name: 'DefaultLayout',
};
</script>

Sample custom page layout

<template>
    <div>
        <TrialBanner v-if="$store.state.website.is_trial"/>
        <div class="page-body-wrapper" class="p-0">
            <div class="main-panel" class="m-0 w-100">
                <div class="content-wrapper" class="p-0">
                    <slot></slot>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
export default {
  name: 'CustomizeLayout',
};
</script>

Main.js: registering layout components as global components

import DefaultLayout from '@/layouts/DefaultLayout.vue';
import CustomizeLayout from '@/layouts/CustomizeLayout.vue';

Vue.component('default-layout', DefaultLayout);
Vue.component('customize-layout', CustomizeLayout);

Router.js: defining layouts for each route

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,    
  },
  {
    path: '/customize',
    name: 'customize',
    component: CustomizeView,
    meta: {
      layout: 'customize-layout'
    }
  }
];

The <slot></slot> in each layout component is where the View will render. You can also have multiple named slots and named views if you want to render different components in areas per layout.

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

Discover the process of creating a dynamic mailto link using AJAX and HTML

One of my tasks involves extracting email addresses from an XML document using AJAX, and then displaying them on a webpage as clickable links for sending emails. Here is a snippet of JavaScript code I am working with: emailobj = listings[i].getElementsBy ...

Difficulty arises in displaying angle brackets while using the xml-builder node package

While working on creating an XML file using the "xml-builder" node module, I encountered an issue with angle brackets. When attempting to include "<" or ">", the resulting characters showed up as "<" and ">". The code snippet in question is: l ...

`Creating a functional list.js filter``

I'm having trouble making the List.js filter function work properly. The documentation for List.js is not very helpful for someone new to development. Below is the code I am using: HTML: <div class="col-sm-12" id="lessons"> <input class= ...

A step-by-step guide on enabling Autoclick for every button on a webpage

I am currently using Jquery and Ajax to carry out an action, my goal is for a code to automatically click on every button once the page has finished loading. Although I attempted to use the following javascript code to achieve this at the end of my page, ...

Trouble encountered when trying to use an anchor link with the .slideUp jQuery function

Would you be able to assist me with understanding why my anchor links are not functioning correctly? I have 3 anchor links, for example: Google (not working) Yahoo (not working) Facebook (working) Any insights on why Google and Yahoo are not working? &l ...

Can the performance of a system be impacted by node.js cron?

I am looking to incorporate a cron module (such as later or node-cron) into my node server for job scheduling. The jobs in question involve sending notifications (e.g., email) to remind users to update their profile picture if they haven't done so wit ...

Unexpected outcomes when trying to sort and paginate React-Table

Experiencing unexpected results with react-table integration for pagination and sorting. Merged examples from the react-table repository. Encountering an issue where table hooks reset the page index on re-render, causing fetchData to be called twice during ...

Converting Database Information to JSON Format for Mobile Authentication Form

Currently, I am working on a Mobile App project using Phonegap that requires users to log in before retrieving JSON data. This PHP page is responsible for connecting to the mobile site and fetching the necessary information. <?php $con = mysqli_connec ...

There seems to be a problem with completing the Axios post request in the Javascript Front

My front-end, built with React, is having trouble retrieving data from a third-party API through my Node.js backend. Despite using axios.post request, the response remains undefined and I'm stuck at handling the asynchronous request. It appears that t ...

Troubleshooting: Issue with Firebase callable function execution

In my index.js file, I have the following code snippet: const firebase = require("firebase"); const functions = require('firebase-functions'); // Firebase Setup const admin = require('firebase-admin'); const serviceAccount = require(&a ...

Resolving Typescript custom path problem: module missing

While working on my TypeScript project with Express.js, I decided to customize the paths in my express tsconfig.json file. I followed this setup: https://i.stack.imgur.com/zhRpk.png Next, I proceeded to import my files using absolute custom paths without ...

The blur() function in -webkit-filter does not seem to function properly in Vue.js

I'm having trouble implementing the -webkit-filter: blur() property. I tried using "filter" instead, but it still isn't working. Could this be a limitation of Vue.js or are there any other solutions available? <template> <div class=&qu ...

Iterating through a nested array in order to dynamically generate elements using JavaScript/jQuery

Seeking assistance with a specific issue I am facing. Despite extensive research on this platform, I have not found a solution to my problem. Recently, I successfully used jQuery each to loop over objects. However, I am currently struggling to iterate thro ...

Searching for a specific row of data by ID in a massive CSV file using Node.js

Can someone recommend an npm package that is ideal for iterating over a csv file, locating a specific value, and updating/appending to that particular row? I don't have any code to display at the moment as I'm in the process of testing different ...

"Error" - The web service call cannot be processed as the parameter value for 'name' is missing

When using Ajax to call a server-side method, I encountered an error message: {"Message":"Invalid web service call, missing value for parameter: \u0027name\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(O ...

Provide the 'URL' of an image in JavaScript

Is it possible to retrieve the image address of an img tag using JavaScript without accessing the src attribute directly? Interestingly, Google Chrome provides a way to copy the image address by right-clicking on an img tag and selecting 'Copy image ...

Having trouble accessing data beyond the login page using Node/Express

Currently in an unusual situation. I am developing a backend and frontend that connects to a third-party RESTFUL API managing some hardware. The third-party API is hosted on your local system as a webserver, meaning HTTP requests are directed to "localhost ...

Changing the color variable of an object using an onClick function in JavaScript

I'm currently working on a simple game where users can draw using the keys W, A, S, and D. If you want to take a look at the progress I've made so far, here is a JSFiddle link. There's a collision function in the code that I no longer need, ...

What is the process for transforming a promise outcome into JSON format?

My current challenge involves using axios to retrieve JSON data from an external API in my backend and then passing it to the frontend. The issue arises when I attempt to log the result in the frontend, as all I see is a promise object instead of the actua ...

Vue: navigating to a specific id using scroll is malfunctioning

I have integrated the vueToScroll library to enable scrolling to a dynamically created element with a specific id. <button ref="replyBtn" v-scroll-to="{ el: '#goToReply101', duration: 800, easing: 'easi ...