How to display a modal within a router-link in Vue 3?

Below are buttons with router-links. However, I only want the calculator button to open a modal. When I execute the code provided, all buttons trigger the modal instead of just the calculator button.

Output:

https://i.sstatic.net/layQ1.png

Router-link Code:

  <div class="container menu-title">
      <div class="shortcuts-horizontal pt-2 pb-2">
        <template v-for="(menuItem, j) in item.shortcuts" :key="j">
          <div class="menu-item btn-margin">
            <router-link
              class="menu-link shortcut-btn"
              active-class="active"
              :to="menuItem.route || menuItem.modal"
              data-bs-toggle="modal"
              data-bs-target="#calculator"
            >
              <span v-if="menuItem.svgIcon" class="menu-icon svg-margin">
                <span class="svg-icon svg-icon-4">
                  <inline-svg :src="menuItem.svgIcon" />
                </span>
              </span>
            </router-link>
          </div>
        </template>
      </div>
    </div>

Modal Code:

  <div class="modal fade" tabindex="-1" id="calculator">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title">Modal title</h5>
              </div>
            </div>
          </div>
        </div>

Menu.ts Code:

 shortcuts: [
      {
        route: "/activities/add/",
        svgIcon: "/media/icons/duotune/art/art002.svg",
        fontIcon: "bi-app-indicator",
      },
      {
        route: "/quotes/add/",
        svgIcon: "/media/icons/duotune/finance/fin010.svg",
        fontIcon: "bi-app-indicator",
      },
      {
        route: "/price-analysis/add/",
        svgIcon: "/media/icons/duotune/graphs/gra004.svg",
        fontIcon: "bi-app-indicator",
      },
      {
        route: "/projects/add/",
        svgIcon: "/media/icons/duotune/abstract/abs027.svg",
        fontIcon: "bi-app-indicator",
      },
      {
        modal: "#calculator",
        svgIcon: "/media/icons/duotune/finance/fin007.svg",
        fontIcon: "bi-app-indicator",
      },
    ],

Answer №1

In my approach, I see modals as child components within the router view. To display them as popups over the content, I utilize a

<Teleport to="#modals">
.

Router setup:

{
      path: '/',
      name: 'Home',
      component: YourPage,
      children: [
        {
          path: 'calculator',
          component: CalculatorModal,
        }
      ]
    }

Modal structure:

<Teleport to="#modals">
        <div class="modal fade" tabindex="-1" id="calculator">
              <div class="modal-dialog">
                <div class="modal-content">
                  <div class="modal-header">
                    <h5 class="modal-title">Modal title</h5>
                  </div>
                </div>
              </div>
            </div>
    </Teleport>

Answer №2

Consider incorporating the modal library into your project. Your code may resemble the following:

import Modal from "Modal.vue"

const routes = [
    {
        path: "/calculator",
        component: useModalRouter(Modal)
    }
]

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

Cancelling an ongoing AWS S3 upload with Angular 2/Javascript on button click

I'm currently working with Angular 2 and I have successfully implemented an S3 upload feature using the AWS S3 SDK in JavaScript. However, I am now facing a challenge: how can I cancel the upload if a user clicks on a button? I've attempted the ...

Activate ajax search in select2 by hand

I recently integrated the select2 plugin with jQuery into my website. For the most part, it functions perfectly. One particular feature I have is a search widget that utilizes select2 and remote data search. When I enter a search query using a keyboard ...

Encountering a problem with AngularJS - receiving the [ng:areq] error, for more information visit http://errors.angularjs.org/1.3.2/ng/areq

While working on my CRUD angularApp, I encountered a strange error in Chrome dev tools. Here is the complete error message: error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=DbController&p1=not%20a%20function%2C%20got%20string at angular.j ...

Show all column data when a row or checkbox is selected in a Material-UI datatable

I am currently working with a MUI datatable where the properties are set as below: data={serialsList || []} columns={columns} options={{ ...muiDataTableCommonOptions(), download: false, expa ...

Is there a way to locate child components without needing to designate the higher-order component encompassing them?

When working with Material-ui, I often find that its extensible nature can be a hindrance when it comes to testing. For example, even if I am using the following code: const MyEventButton = () => (<IconButton /> <Event /> </IconButton ...

Tips for applying an active class to buttons using ng-click?

Here is the HTML code for the buttons. The taskfilter is the filter that controls how the buttons work when clicked and the class name is 'sel' <a class="clear-completed" ng-click="taskfilter = 1" ng-class="{'sel':enabled}"> &l ...

Using setTimeout() and clearTimeout() alongside Promises in TypeScript with strict mode and all annotations included

Many examples of timer implementations using Promises in JavaScript seem overly complex to me. I believe a simpler approach could be taken. However, I am looking for a solution specifically tailored for TypeScript with the "strict": true setting and all ne ...

Learn how to make a mesh in Three Js React refract its environment while keeping the background hidden from the camera

I've been grappling with this challenge for quite some time now, so any assistance would be highly valued! My aim is to create the illusion of an image being confined within a mesh structure. My initial idea was to utilize a mesh with defined thickne ...

Reactive forms in Angular now support changing focus when the Enter key is pressed

I have successfully created a table and a button that generates dynamic rows with inputs inside the table. One issue I'm facing is that when I press enter in the first input, a new row is created (which works), but I can't seem to focus on the ne ...

Guide to inheriting functions from a parent component in Angular 2

Hello, I am a beginner in the realm of angular2 and would appreciate any assistance in refining my vocabulary and terminology. Currently, I have a class that consists of two directives structured as follows: In parent.component.ts, the Parent component i ...

The browser unexpectedly cancelled the ajax call triggered by the beforeUnload event

Seeking advice on a web application that needs to save user input data through an ajax call when they leave the site. Currently using "Fetch" in a beforeunload event listener, but encountering issues with browsers cancelling the ajax call (specifically th ...

Php/JavaScript Error: Identifier Not Found

I've double-checked my code multiple times, but it still doesn't seem to be working properly. When the PHP runs, the browser console displays the following error: Uncaught SyntaxError: Unexpected identifier. I'm not sure if this is a si ...

How to switch around div elements using CSS

There are two unordered list items in a container div and one swap button. When the swap button is clicked, the order of items needs to change. This functionality can be achieved using the following swap function. var ints = [ "1", "2", "3", "4" ], ...

unorthodox method of transmitting parameters within express.js source code

While searching for the source code of express router, I came across this interesting piece: var debug = require('debug')('express:router:route'); I am curious to know more about this unusual way of passing arguments. Can someone ...

What are the best practices for updating models using Bookshelf.js?

I'm struggling to make sense of the Bookshelf API, particularly when it comes to performing upsert operations. Let me outline my specific scenario: My model is named Radio, with a custom primary key called serial. For this example, let's assume ...

Creating impenetrable div elements with JavaScript or jQuery

I'm currently working on creating solid blocks using DIVs positioned side by side both horizontally and vertically. I've successfully achieved this when the divs have equal heights. However, an issue arises when a div has larger dimensions; it en ...

Can a sophisticated text editor be utilized without a content management system?

Many website builders utilize rich text editors as plugins to enhance content creation, such as in CMS platforms like Joomla and WordPress. However, can these same editors be easily integrated into a custom website built from scratch using just HTML, PHP ...

What could be the reason why document.getElementsByClassName does not seem to be functioning properly within

I've come across this code snippet const desc_object = document.getElementsByClassName("singlePostDesc"); console.log(desc_object[0]); This is how it appears in JSX {updateMode ? ( <> ...

Dynamically binding image URLs in VUEJS

Below is the JSON data containing button names and their corresponding image URLs: buttonDetails= [ { "name": "button1", "images": [{ "url": "https://localhost:8080/asset/d304904a-1bbd-11e6-90b9-55ea1f18bb ...

Struggling with retrieving the $id variable from the view in both the controller and the database through Ajax

While checking my view, I noticed that the variable $id is visible. However, when I send it through Ajax, it ends up as NULL in the database. The way I'm sending the variable $id from the view using Ajax is like this: $.ajax({ url:'{ ...