【问题标题】:How to use v-for in SweetAlert2 html output如何在 SweetAlert2 html 输出中使用 v-for
【发布时间】:2018-10-10 16:29:10
【问题描述】:

我正在尝试在带有vue-sweetalert2 的警报中显示以下模板:

<input v-model="name" class="swal2-input">

<select v-model="parent" name="parent" class="form-control">
  <option v-for="category in categories" v-bind:value="category.id">
    {{category.name}}
  </option>
</select>

我在普通模板中没有任何问题,但我不知道如何在SweetAlert2中使用它。

我试过这段代码:

this.$swal({
  text: 'edit child',
  html:
   '<input v-model="name" class="swal2-input">' +
   `<select v-model="parent" name="parent" class="form-control">
      <option value="">nothing</option>
      <option v-for="category in categories" v-bind:value="category.id">
        {{category.name}}
      </option>
    </select>`,
  showCancelButton: true,
  confirmButtonText: 'edit',
  cancelButtonText: 'cancel',
  showCloseButton: true,
})

但它什么也没显示。

【问题讨论】:

  • 你把这个放在哪里。$swal( ...?
  • 在我的组件中,正常的 swal() 没有任何问题
  • 你有错误吗?
  • 不,但它只是给我看 {{caregory.name}}
  • 你的汗水警报内容超出了 Vue 范围

标签: javascript vue.js vuejs2 sweetalert2


【解决方案1】:

由于传递给 SweetAlert2 的 HTML 不由 Vue 处理,模板机制(包括 v-forv-model)将不可用,因此您必须使用 JavaScript 手动创建模板。具体来说,您将替换:

html: `<input v-model="name" class="swal2-input">
<select v-model="parent" name="parent" class="form-control">
  <option v-for="category in categories" v-bind:value="category.id">{{category.name}}</option> ...`

与:

html: `<input id="my-input" value="${this.name}" class="swal2-input">
<select id="my-select" value="${this.parent}" name="parent" class="form-control">
  ${this.categories.map(cat => `<option value="${cat.id}">${cat.name}</option>`)} ...`

注意&lt;input&gt;&lt;select&gt; 被赋予了ID,以便我们可以fetch the values 对警报进行“预确认”:

const {value} = this.$swal({
  preConfirm: () => [
    document.getElementById("my-input").value,
    document.getElementById("my-select").value
  ]
});
console.log(value[0]); // value of my-input
console.log(value[1]); // value of my-select

demo

【讨论】:

  • 它给我 ${this.categories.map(cat => &lt;option value="${cat.id}"&gt;${cat.name}&lt;/option&gt;)} 上的错误
  • 我无法在 switalert html 输出中使用 ${}
  • 它需要位于您已经在使用的模板文字字符串中(如问题所示)。您可以编辑demo 以重现该问题吗?
  • @MahdiMirhendi 没问题 :)
猜你喜欢
  • 1970-01-01
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
  • 2020-12-12
  • 1970-01-01
  • 2021-10-28
  • 2016-12-05
  • 1970-01-01
相关资源
最近更新 更多