Search code examples
vue.jssweetalert2v-for

How to use v-for in SweetAlert2


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

I've tried this code, but this is what it looks like in html.

{{ item.school_name }}

How can i do?

I've not use "Sweetalert 2, I hope you'll understand if i can't.


Solution

  • vue-sweetalert2 doesn't support rendering HTML templates dynamically, so you can't pass Vue templates this way; but you don't really need to in this case. Instead, you could generate the HTML string in JavaScript like this:

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

    The above code uses Array.prototype.map on the array in response.data.data.schools to map the array values into an array of divs. Then it uses Array.prototype.join to combine the resulting array values into one long HTML string.

    demo