在Sweetalert2内容中使用Vue组件

ang*_*ala 4 javascript vue.js sweetalert2

我在Vue项目中有一些普通的Sweetalert2模态。我想在警报中使用自定义组件。例如:

<template>
  <h1>Hello {{name}}</h1>
</template>
<script>
module.exorts: {
  props: ["name"]
}
</script>
Run Code Online (Sandbox Code Playgroud)

my_template.vue

而且,在我的Sweetalert模式中:

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

我不确定这是否可行或如何实现。

soe*_*eik 5

从技术上看,这可能是:

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>'
  })
})
Run Code Online (Sandbox Code Playgroud)

但是您可能需要将其包装在一个函数中。看看我的小提琴:

JS小提琴

这只是一个主意,对我来说,它看起来并不好,但是仍然可以运行。我还要提到的是,每次以这种方式打开对话框时,都将创建vue的新实例。

选项2从评论到我的答案:

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

swal({
    html: "<my-component></my-component>"
})

new Vue({
    el: swal.getContent()
})  
Run Code Online (Sandbox Code Playgroud)

小提琴

  • @KirillStepanov 我目前使用的是 `html: '&lt;div id="swalHtml"&gt;&lt;/div&gt;'`,然后在 `onBeforeOpen:` 中使用 `let ComponentClass = Vue.extend(MyComponent); let instance = new ComponentClass({ propsData: { item: this.item } })` 在上下文中扩展 vue 组件,然后将其挂载到 dom `instance.$mount(); document.getElementById('swalHtml').appendChild(instance.$el)`。 (4认同)
  • 或者甚至更好:`html:'&lt;my-component&gt; &lt;/ my-component&gt;'`,然后是`new Vue({el:swal.getContent()})`` (3认同)