programing

SweetAlert2 html 출력에서 v-for를 사용하는 방법

prostudy 2022. 4. 15. 21:34
반응형

SweetAlert2 html 출력에서 v-for를 사용하는 방법

다음 템플릿을 경고에 표시하려는 경우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,
})

아무것도 안 보여

SweetAlert2에 전달된 HTML은 Vue에서 처리되지 않으므로 템플릿 메커니즘(포함)v-for그리고v-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>`)} ...`

참고:<input>그리고<select>경고의 "사전 확인"에 대한 값을 가져올 수 있도록 ID가 제공됨:

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

데모를 하다

참조URL: https://stackoverflow.com/questions/52744878/how-to-use-v-for-in-sweetalert2-html-output

반응형