Stop the primary router-view from being altered

Within my Vue application, I have a main component that contains the following router views:

<router-view></router-view>
<div class="modal">
  <router-view name="modal"></router-view>
</div>

In various sections of the app, I need to open specific router links that trigger a modal to appear. To achieve this functionality, I created a route in the following manner:

{
    path: '/visitors/login',
    props: true,
    components: {
        modal: ModalLogin
    },
    meta: {
        modal: true,
    }
},

By implementing this route, the designated modal component is loaded into the modal router view. However, one downside is that the default router view is cleared in the process. Is there a solution to retain the content in the default router view while only updating the modal router view?

Answer №1

After receiving feedback on my previous comment, I decided to take a different approach instead of attempting to map a modal to a specific route. I created a demo using Vue 2 and the CLI to showcase this implementation.

When navigating to either the / or /visitors routes, the Visitors component/page will be displayed. By clicking the 'Login' button, you can trigger the modal to open.

If you specifically type in the route /visitors/login in the browser's address bar, the modal will be displayed on top of the Visitors page.

router/index.js

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
import Visitors from '../Visitors.vue'

const routes = [
  {
    path: '/',
    redirect: 'visitors'
  },
  {
    name: 'visitors',
    path: '/visitors/:modal?',
    component: Visitors,
    props: true
  }
]

export default new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

App.vue

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

<script>
  export default {
    name: 'App',
    components: {
    },
    data() {
      return {
      }
    }
  }
</script>

Visitors.vue

<template>
  <div class="visitors">
    <h4>Visitors</h4>
    <div class="row">
      <div class="col-md-4">
        <button class="btn btn-secondary" @click="showModal">Login</button>
      </div>
    </div>
    <login-modal v-if="displayLogin" @login-event="login" @close-modal-event="hideModal" />
  </div>
</template>

<script>
  import LoginModal from './LoginModal.vue';

  export default {
    components: {
      LoginModal
    },
    props: {
      modal: {
        type: String,
        required: false
      }
    },
    data() {
      return {
        displayLogin: false
      }
    },
    methods: {
      showModal() {
        this.displayLogin = true;
      },
      hideModal() {
        this.displayLogin = false;
      },
      login(user) {
        this.hideModal();
        // Process login
        console.log(user);
      }
    },
    created() {
      if (this.$route.params.modal) {
        if (this.$route.params.modal === 'login') {
          this.displayLogin = true;
        }
      }
    }
  }
</script>

LoginModal.vue

<template>
  <div class="login-modal">
    <div class="modal" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Login</h5>
            <button type="button" @click="closeModal">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <form @submit.prevent="login">
              <div class="form-group">
                <label for="username">User Name</label>
                <input type="email" class="form-control" id="username" v-model="user.name">
              </div>
              <div class="form-group">
                <label for="password">Password</label>
                <input type="password" class="form-control" id="password" v-model="user.password">
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" @click="login">Login</button>
            <button type="button" class="btn btn-secondary" @click="closeModal">Close</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        user: {
          name: '',
          password: ''
        }
      }
    },
    methods: {
      closeModal() {
        this.$emit('close-modal-event');
      },
      login() {
        this.$emit('login-event', this.user)
      }
    }
  }
</script>

<style scoped>
  /* Override default value of 'none' */
  .modal {
    display: block;
  }
</style>

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

Can someone provide guidance on effectively implementing this JavaScript (TypeScript) Tree Recursion function?

I'm currently grappling with coding a recursive function, specifically one that involves "Tree Recursion". I could really use some guidance to steer me in the right direction. To better explain my dilemma, let's consider a basic example showcasi ...

Certain files in the HTML report generated by ESLint may not display any output

When using eslint to generate an HTML report, I am encountering some issues. Within my package.json, the configuration is as follows: "eslint-html": "eslint --format html ./src/* -o ./dist/eslint/index.html", The resulting report in the file ./dist/esli ...

Error: Provider not recognized

Currently, I am in the process of creating a basic chat application using express.js, socket.io, and angular. The functionality seems to be working properly. However, I am encountering an issue where the socket message event is not synchronizing and displa ...

Use Vue's DOM manipulation to properly surround iframes with divs

I'm facing a scenario where my Vue component displays HTML content retrieved from the database in the following format: <div id="post-body-text" class="post__main-text" v-html="postText" ...

Modify the CSS to update the navbar's active color

I'm currently using a simple CSS top navbar (without Bootstrap or any other framework) and I want to be able to change the active page's button color. For example, when I navigate to the home page, I want the button in the navbar to turn red or a ...

Top method for centering a flexible SVG vertically once the page width becomes too narrow

Currently, I have two SVG images displayed side by side on a webpage. One SVG needs to maintain a fixed size while the other should scale as needed, and I have achieved this functionality. However, I am facing an issue where I want the two SVGs to align v ...

Exploring the relationships between schemas in Node.js using Mongoose and MongoDB

Hello, I am a beginner in utilizing MongoDB and Node.js and I have a query. Below is my product schema: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const categorySchema = require('./category'); const Produc ...

iframe-based cross-site file upload

I created an image uploading API and implemented a jQuery plugin that utilizes an iframe for the upload process. However, due to the API's domain being different, I am unable to retrieve the return data from the iframe. Is there a solution to accessin ...

What is the best method for choosing a document from a Firebase based on its creation time?

Currently delving into Firebase as part of my project, struggling with setting queries in the Database. I've provided a breakdown of my Firebase database structure below: Looking to retrieve the most recently created document from the 'subscrip ...

Prevent users from navigating back to the previous page in ASP.NET

After trying, I noticed that the back page briefly appears for 1 or 2 seconds before returning to the current page. I want to completely avoid going to the back page, even for just a second. <script type="text/javascript"> function prev ...

Populate a dropdown list with array elements using Javascript in ReactJS

I am encountering an issue while trying to populate a dropdown with data from the 'options' array. The error message states that it cannot read property appendChild of null. Using 'document.getElementByClassName' instead of document.ge ...

"Unraveling the Mystery of jQuery In

I am facing an issue with integrating jQuery into my code. I have always followed the same method, which has worked in the past, but now it seems to be causing problems for me. I suspect it may be because I am not on my usual laptop, although when I visite ...

Automatically trigger a Bootstrap 5.2 modal when the page loads

Currently, I've been utilizing Bootstrap in conjunction with JQuery and have a specific code snippet that displays a Modal when a page is loaded. However, with the latest version 5.2 of Bootstrap, there is a push to move away from using JQuery (which ...

Creating a function that allows for the dynamic addition of rows in Angular with

I am currently working on implementing search and filter functionality, which requires adding rows dynamically. With hundreds of fields to filter, my boss has decided to organize them in dropdown menus (such as Manager, City, and Name in this example). The ...

Applying REGEX on input text in React Native

I'm having trouble getting my regex function to work correctly, so I believe there might be an error in my code. Any assistance would be greatly appreciated. Here is the regex function I am using: let validatePlate = (plate) => { var re = /(^[A ...

I am looking to incorporate two YouTube videos into an HTML webpage, each in a different language. I would like to provide the option for users to select the language, even though the content

I am looking to target a global audience with my website, so the content is in English. However, I want to offer users the option to watch videos in their preferred language. I have recorded content in 4 different languages that might enhance engagement on ...

NodeJs ERROR: Module not found

When trying to launch an instance running ubuntu with express, I encountered a module not found error that does not occur on my Windows machine. Error Message: node:internal/modules/cjs/loader:1085 throw err; ^ Error: Cannot find module './src/c ...

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 ...

Parsing JSON data in array format sent from jQuery and processed by Node.js

I'm currently experimenting with Node Js and working on an app for learning purposes. In this app, I aim to send data from an HTML form using jQuery/AJAX and have Node Js/Express handle and process the data. Here is the HTML code containing a series ...

Delete the class when the user clicks anywhere on the page

I have 2 buttons that will toggle/remove a class when the user clicks on them. $('.social-toggle').on('click', function() { $('.social-networks').not($(this).next()).removeClass('open-menu') $(this).next().toggl ...