Utilizing Vue components within SweetAlert2 content

I have a couple of basic Sweetalert2 pop-up modals within a Vue project. My goal is to incorporate a custom component into one of the alerts. For instance:

<template>
  <h1>Greetings {{name}}</h1>
</template>
<script>
module.exorts: {
  props: ["name"]
}
</script>

my_template.vue

Subsequently, in my sweetalert modal:

swal({
  titleText: "Hello",
  html: '<my-template name="greeting"></my-template>'
});

I'm uncertain if this is even feasible or how it can be accomplished.

Answer №1

Seemingly, it is technically feasible:

Vue.component('my-component', {
  template: '<div>A custom component!</div>'
})

new Vue({
  el: '#modal',
  beforeCreate:  swal({
    titleText: "Hi",
    html: '<div id="modal"><my-component></my-component></div>'
  })
})

However, it may be advisable to encapsulate it within a function. Please refer to my demonstration on JS Fiddle:

JS Fiddle

This approach might not be aesthetically pleasing, but it is functional. Additionally, it should be noted that creating a new instance of Vue every time the dialog is opened using this method.

Option 2 as suggested in a comment to my answer:

Vue.component('my-component', {
    template: '<div>A custom component!</div>'
})    

swal({
    html: "<my-component></my-component>"
})
  
new Vue({
    el: swal.getHtmlContainer()
})  
 

Fiddle

Answer №2

To display hidden content within your app, follow these steps:

<div id="hiddenContent" style='display: none'>
  <my-template name="welcome"></my-template>
</div>

Next, retrieve the innerHTML of the element and show it in an alert:

let element = document.getElementById('hiddenContent');
swal({
  html: element.innerHTML
});

Answer №3

After some tinkering, I've successfully gotten it to function in the following way:

I encapsulate all the logic of the template within backticks: ` `

Additionally, you'll need to modify the vue.config.js file and insert this line inside the configureWebpack object: 'vue$':'vue/dist/vue.esm.js'

configureWebpack: {
resolve: {
  alias: {
    'src': resolveSrc('src'),
    'chart.js': 'chart.js/dist/Chart.js',

    // add this line for including components inside swal alert
    'vue$':'vue/dist/vue.esm.js'
  }
 }
}

Once these modifications are made, be sure to restart the project using "npm run dev"

Here's a complete example that I have personally tested and confirmed to be working:

openSweet() {
  Vue.component('my-comp', {
      template: `
            <div class="card-content">
              <div class="span2">
                    <div class="col-sm-6 col-md-2 col-lg-3">
                        <div class="row">
                          <div style="margin-top: 6px;" >
                            <p-switch v-model="switchTrip.state" type="primary" 
on-text="ON" off-text="OFF" style="justify-content:center"></p-switch>
                            <h5 class="card-title" style="margin-left: 
25px;">Recorridos</h5>
                          </div>
                        </div>

                        <div class="row">
                          <div style="margin-top: 6px;" >
                            <p-switch v-model="switchVel.state" type="primary" 
on-text="ON" off-text="OFF" style="justify-content:center"></p-switch>
                            <h5 class="card-title" style="margin-left: 
25px;">Velocidad</h5>
                          </div>
                        </div>

                    </div>
              </div>
              <div class="span2">
                    <div class="col-sm-6 col-md-4 col-lg-3">
                        <div class="row">
                          <div >
                            <input type="search" class="form-control input-sm" 
placeholder="km / h" v-model="vmax">
                            <h5 class="card-title">Vel. Max</h5>
                          </div>
                        </div>

                        <div class="row">
                          <div>
                            <input type="search" class="form-control input-sm" 
placeholder="minutos" v-model="tol">
                            <h5 class="card-title">Tolerancia</h5>
                          </div>
                        </div>
                    </div>
              </div>
            </div>
      `,
    data () {
      return {
        switchVel: {
          state: false
        },
        switchEvent: {
          state: false
        },
        switchTrip: {
          state: false
        },
        search: '',
        vmax: '',
        tol: ''
      }
    },
    components: {
        [Button.name]: Button,
        Card,
        PSwitch
    }
  })
  new Vue({
    el: '#modal',
    beforeCreate:  () => {
      swal({
        titleText: "Descarga de Reportes",
        showCancelButton: true,
        cancelButtonText: 'Cancelar',
        confirmButtonText: 'Descargar',
        // confirmButtonAriaLabel: 'glyphicon glyphicon-ok-sign',
        // cancelButtonAriaLabel: 'glyphicon glyphicon-remove-sign',
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        width: 800,
        html: '<div id="modal"><my-comp></my-comp></div>'
      })
    }
  })
}

I trust that this explanation proves helpful.

Best regards

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

Setting up a function in React to utilize an image stored in state

I have a function in my react component for image classification that retrieves the image from the img tag using document.getElementById: const img = document.getElementById('animal_image');. The image uploaded via the file input updates the sta ...

Transfer your documents effortlessly as soon as they are

I am having trouble implementing an automatic file upload feature without the need for a separate upload button. Below is the code I have so far, excluding the irrelevant CSS. //html <!-- some codes here--> <input type="file" id="f ...

Is there a way for me to obtain the full error message after a failed fetch request?

I'm trying to capture all errors from the fetch function, including the specific red highlighted details as a string: https://i.sstatic.net/GtHxv.png But when I catch an error in my code, all I get is "Failed to fetch." Here's what my code looks ...

Javascript error when attempting to add leading zeros

Is there a way to utilize JavaScript or JQuery in order to prepend a zero to this script? for (im=1;im<=31;im++){ days[im]=everyDay[im]; } ...

I possess multiple checkboxes that appear as described below. I am looking to modify the nested value highlighted in the blue circle in the image

I need to make a change in this area of my state: view screenshot The specific portion highlighted in the circle is what I want to modify **Here is my checkbox input code:** {this.state.data.map((elm) => ( <div className={classes.rowContainer}&g ...

I'm interested in learning about the most efficient practices for handling JSON, performing math operations, and utilizing loops in JS/React. What techniques

Short version: I'm working with a large array of JSON objects (60K+ elements) in my application I need to perform various mathematical operations such as comparison and addition Currently, I am handling this through multiple for loops (simplified ...

Populate Chart.js with data retrieved using the $http.get() method

Looking to retrieve data from a webservice and present it in a chart, I decided to use Chart.js specifically with tc-angular-chartjs. The $http.get( ) call I'm using for testing is: $http.get('http://myjson.com/1chr1').success(function(data ...

Defining the flow and functionality

I'm currently attempting to define a function signature using Flow. I had anticipated that the code below would generate an error, but surprisingly, no errors are being thrown. What could be causing this issue? // This function applies another functi ...

Why are all the values in my list appearing as undefined after parsing with JSON?

Just starting out with this project. I'm attempting to print a list, where the names come from a button. However, all the names are showing up as undefined. I suspect it has something to do with local storage, but I can't pinpoint the issue. < ...

"What is the syntax for pushing an object onto an array within an array in AngularJS

Looking to create an object structure like the one below: $scope.allBooks = { books:[ { name:"", id:"" } { ...

Error: 'require is not defined' pops up while trying to import into App.js for a React App built with CDN links

My latest project involves a React App that showcases an h1 tag saying "Hello World" on the browser. Rather than utilizing npm, I have opted for CDN links to set up the application. The structure of the App consists of three key files: An index.html file ...

Set a variable to store the loaded 3D object and receive an undefined value in return

I've been working on a function to load 3D objects using three.js. My goal is for this function to return the 3D object once it's loaded, but no matter what I try, I keep getting "undefined". function load3DObject(url, meshMaterial) { let mes ...

Guide to creating unit tests for document.URL in Angular 5 specifications

Currently attempting to simulate document.URL = 'dashboard'; however, encountering an issue where it states that I can't assign to url because its readonly property. This problem arose while writing jasmine test cases click here for image de ...

Updating a connected model in Sequelize using another model

Seeking guidance on updating a model with new associations in Sequelize. The model involves a many-to-many relationship with a join table. Attempted this code snippet: app.patch('/api/team/:id/newplayers', function(request, response){ const pl ...

Learn how to replace the current window with a new window in Electron

I have successfully created a new window that opens when clicking a button, but it currently appears as a pop-up window. How can I make the new window replace the main window instead? var app = require('app') var BrowserWindow = require('br ...

Choose a specific <div> element by its unique ID and trigger a click event on it as soon as the page loads

There is a div element on my webpage tagged with the ID of #activateeditbutton. I am hoping to have this specific div trigger a click event upon the page's initial loading. In an attempt to achieve this functionality via jQuery, I have written the fo ...

The elusive cookie in NodeJS remained just out of reach

After setting a cookie using the code below: router.get("/addCartToCookie", function(req, res) { let options = { maxAge: 1000 * 60 * 15, httpOnly: true, }; let cartData = { name: "test cookie", slug: slugify(&quo ...

The pop-up window created programmatically refuses to close

I am struggling with an issue where I am opening a pop-up from the code behind as a waiting image while processing some background activities. However, the pop-up does not close after the activity is done. Can someone please help me figure out what I am ...

How to make an input blur in Angular 2 when a button is clicked?

Is there a way to blur an input field by pressing the return button on a mobile native keyboard? Here is an example: <input type="text" #search> this.search.blur() //-- unfocus and hide keyboard ...

Tips for passing a page as an argument in the function parameter of the page.evaluate() method?

I keep running into this issue when I pass the page as an argument: TypeError: Converting circular structure to JSON --> commencing at object with constructor 'BrowserContext' | property '_browser' -> object with const ...