Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 785
angrykoala Avatar asked Feb 08 '18 10:02

angrykoala


2 Answers

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

like image 98
soeik Avatar answered Oct 11 '22 15:10

soeik


You can render and hide the content inside your app:

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

Then pass the element's innerHTML to the alert:

let el = document.getElementById('swalHTML')
swal({
  html: el.innerHTML
});
like image 20
opowell Avatar answered Oct 11 '22 15:10

opowell