vue.js - 如何在 SweetAlert2 中使用 v-for

标签 vue.js sweetalert2 v-for

this.$swal
.fire({
  title: '학교를 검색해주세요.',
  input: 'text',
  inputAttributes: {
    autocapitalize: 'off'
  },
  showCancelButton: true,
  confirmButtonText: '검색하기',
  cancelButtonText: '취소',
  icon: 'question',
  preConfirm: (school) => {
    return axios.get(`(serverIp)/school?query=${school}`)
      .then(response => {
        console.log(response.data.data.schools)
        this.$swal.fire({
          title:'학교를선택해주세요.',
          html: `<div v-for="(item, index) in response.data.data.schools" :key="index">
                     {{ item.school_name }}
                 </div>`
            })
          })
      },
      allowOutsideClick: () => !this.$swal.isLoading()
 })

我试过这段代码,但这是它在 html 中的样子。

{{ item.school_name }}

我该怎么办?

我没有使用“Sweetalert 2,如果我不能,希望您能理解。

最佳答案

vue-sweetalert2 不支持动态渲染 HTML 模板,所以你不能通过这种方式传递 Vue 模板;但在这种情况下你真的不需要。相反,您可以像这样在 JavaScript 中生成 HTML 字符串:

axios
  .get(apiUrl)
  .then(response => {
    this.$swal.fire({
      html: response.data.data.schools
              .map(item => `<div>${item.school_name}</div>`)
              .join('')
    })
  })

以上代码使用Array.prototype.mapresponse.data.data.schools 中的数组上,将数组值映射到 div 的数组中。然后它使用 Array.prototype.join将生成的数组值组合成一个长 HTML 字符串。

demo

关于vue.js - 如何在 SweetAlert2 中使用 v-for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60016874/

相关文章:

javascript - 将 for 循环中每个项目的值设置为 true 或 false

javascript - 如何将类切换到 v-for 中的单个元素

javascript - 使用 Browserify 时使我的 Vue 实例成为全局实例,以便开发人员工具可用

javascript - SweetAlert2:意外的 html 类型!期望 "string",得到对象

button - SweetAlert2 - 绑定(bind)另一个事件以取消按钮?

javascript - SweetAlert2 确认后禁用外部点击

laravel - 在<a>标签的href中编写VueJS数据绑定(bind)表达式

javascript - Vuejs Webpack压缩插件不压缩

github - 在我的Vue项目中使用来自GitHub的组件。 (我是一个完整的初学者)

vue.js - 如何在 v-for 和 v-on :click? 中获取索引和事件