Search code examples
javascriptvue.jssweetalert2

Using vue component in sweetalert2 content


I have a few plain Sweetalert2 modals in a Vue project. I want to use a custom component inside an alert. For example:

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

my_template.vue

And, in my sweetalert modal:

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

I'm not sure if this is even possible or how to do it.


Solution

  • Technically it looks possible:

    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>'
      })
    })
    

    But you may want to wrap it in a function. Take a look at my fiddle:

    JS Fiddle

    It's just an idea, for me it doesn't look good, but still working. Also I have to mention, that you will create new instance of vue every time you open your dialog this way.

    Option 2 from 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