>  기사  >  웹 프론트엔드  >  Alpine JS를 사용한 동적 테이블 생성

Alpine JS를 사용한 동적 테이블 생성

PHPz
PHPz원래의
2024-07-31 12:09:42548검색

Dynamic Table Creation with Alpine JS

이 기사에서는 경량 JavaScript 프레임워크인 Alpine JS를 사용하여 동적 테이블을 만드는 방법을 살펴봅니다. 기본 시나리오와 복잡한 시나리오에 초점을 맞춰 프로세스를 머리글, 본문, 바닥글의 세 부분으로 나누어 보겠습니다.

설정:

  1. HTML 구조: x-data 지시문이 첨부된 기본 HTML 요소()로 시작합니다. 이 지시문은 반응 데이터를 요소에 바인딩합니다.
  2. JavaScript 데이터: 테이블 데이터를 보관하기 위해 HTML 외부에 빈 JavaScript 개체(데이터)를 정의합니다.
  3. 초기 코드는 아래와 같습니다.

    <div x-data="data">
    </div>
    
    <script>
    let data = {
    }
    </script>
    

    헤더

  • 헤더에는 thead 요소를 사용합니다.
  • x-for 지시문은 table.customHeader 데이터를 반복하여 행과 열을 동적으로 생성합니다.
  • 복잡한 헤더는 colspan 및 rowspan 속성(col.attr에 정의됨)을 활용하여 셀을 병합할 수 있습니다.
  • 각 셀 내의 콘텐츠는 x-html을 사용하여 표시되고 col.title 속성에 바인딩됩니다.
<thead class="sticky top-0 z-10 text-gray-700 bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
  <template x-for="row in table.customHeader">
    <tr>
        <template x-for="col in row">
            <th class="px-4 font-semibold text-left border-b py-1.5"
                x-init="col.attr && Object.keys(col.attr).forEach(e => $el.setAttribute(e, col.attr[e]))">
                <div class="flex items-center justify-center">
                    <span x-html="col.title" class="whitespace-nowrap"></span>
                </div>
            </th>
        </template>
    </tr>
  </template>
</thead>
let data = {
  table: {
      customHeader: [
          [
              { title: 'City', attr: { rowspan: 2 }, class: 'border-r border-t' },
              { title: 'Clothes', attr: { colspan: 3 }, class: 'border-r border-t' },
              { title: 'Accessories', attr: { colspan: 2 }, class: 'border-t' }
          ],
          [
              { title: 'Trousers', class: 'border-r' },
              { title: 'Skirts', class: 'border-r' },
              { title: 'Dresses', class: 'border-r' },
              { title: 'Bracelets', class: 'border-r' },
              { title: 'Rings' },
          ]
      ],
  }
}

  • tbody 요소는 테이블의 데이터 행을 보유합니다.
  • x-for를 사용하여 table.data를 반복합니다.
  • 각 행에는 x 텍스트를 사용하여 해당 개체 속성의 데이터로 채워진 셀(b6c5a531a458a2e790c1fd6421739d1c)이 있습니다.
<tbody>
    <template x-for="(row, idx) in table.data">
        <tr class="border-b dark:border-gray-700">
            <template x-for="(col, icol) in row.columns">
                <td x-bind:class="{ [col.class]: !!col.class }" class="px-3 border-b border-gray-200">
                    <div x-text="col.text"></div>
                </td>
            </template>
        </tr>
    </template>
</tbody>

그리고 이것이 우리가 보여주고 싶은 데이터입니다:

data: [
    { "city": "Mandalay", "trousers": 79, "skirts": 16, "dresses": 14, "bracelets": 69, "rings": 99 },
    { "city": "George Town", "trousers": 68, "skirts": 24, "dresses": 90, "bracelets": 96, "rings": 48 },
    { "city": "Gent", "trousers": 26, "skirts": 60, "dresses": 67, "bracelets": 5, "rings": 43 },
    { "city": "Mombasa", "trousers": 34, "skirts": 62, "dresses": 18, "bracelets": 75, "rings": 78 },
    { "city": "Lyon", "trousers": 13, "skirts": 33, "dresses": 12, "bracelets": 0, "rings": 17 },
    { "city": "Vancouver", "trousers": 82, "skirts": 91, "dresses": 18, "bracelets": 96, "rings": 72 },
    { "city": "Cairn", "trousers": 64, "skirts": 43, "dresses": 14, "bracelets": 95, "rings": 55 },
]

보행인

  • tfoot 요소는 바닥글을 정의합니다.
  • 헤더와 유사하게 x-for를 사용하여 table.customFooter 데이터를 반복합니다.
  • 그러나 바닥글은 x-html을 사용하여 table.footerData 내의 속성을 참조하여 동적 값을 표시할 수 있습니다.
<tfoot class="sticky bg-gray-100 -bottom-1">
    <template x-for="row in table.customFooter">
        <tr>
            <template x-for="col in row">
                <td class="px-3 border-b border-gray-200"
                    x-init="col.attr && Object.keys(col.attr).forEach(e => $el.setAttribute(e, col.attr[e]))">
                        <div x-html="table.footerData[col.name)">
                        </div>
                </td>
            </template>
        </tr>
    </template>
</tfoot>
customFooter: [
    [
        { value: 'Total', class: 'font-bold border-r text-center', attr: { rowspan: 2 } },
        { name: 'total-trousers', class: 'text-right border-r' },
        { name: 'total-skirts', class: 'text-right border-r', },
        { name: 'total-dresses', class: 'text-right border-r' },
        { name: 'total-bracelets', class: 'text-right border-r' },
        { name: 'total-rings', class: 'text-right' },
    ],
    [
        { name: 'total-clothes', class: 'text-center border-r', attr: { colspan: 3 } },
        { name: 'total-accessories', class: 'text-center', attr: { colspan: 2 } },
    ],
],

예시 데이터:

도시 이름과 다양한 의류 품목이 포함된 샘플 데이터로 테이블의 기능을 시연합니다.

추가 참고사항:

  • 스타일 지정은 col.class 및 data.class 속성 내에 정의된 CSS 클래스를 사용하여 이루어집니다.
  • 제공된 링크는 추가 탐색을 위한 전체 작업 데모를 제공합니다.

외부 링크

  1. 데모: https://framework.fuwafuwa.web.id/examples/simple-table
  2. 설명: https://framework.fuwafuwa.web.id/docs/simple-table.html#simple-table

결론:

이 분석에서는 Alpine JS를 통해 유연한 머리글, 본문, 바닥글이 포함된 동적 테이블을 만들 수 있는 방법을 보여줍니다. 이 접근 방식은 특히 데이터가 자주 변경되는 시나리오의 경우 테이블 생성 및 관리를 단순화합니다.

위 내용은 Alpine JS를 사용한 동적 테이블 생성의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.