programing

Vuejs 및 데이터 테이블: v-for를 사용하여 데이터를 채울 경우 빈 테이블

prostudy 2022. 5. 20. 21:37
반응형

Vuejs 및 데이터 테이블: v-for를 사용하여 데이터를 채울 경우 빈 테이블

데이터를 얻기 위해 vuejs v-for 지시어와 ajax를 사용하여 데이터 테이블을 채우려고 하는데, 일부 데이터가 표시되어 있음에도 불구하고 표에는 항상 "테이블에 사용 가능한 데이터가 없음"이 표시되고 하단에 "0개 항목 중 0개 항목 표시"라고 표시되어 있다.내 생각에 이것은 Vuejs가 반응적이고 테이블이 변화를 인식하지 못하기 때문인가?한참을 찾아 헤맸지만 해결책이 나오지 않았다.

정말 고마워! :)

템플릿:

<table id="suppliersTable" class="table table-hover table-nomargin table-bordered dataTable">
    <thead>
        <tr>
            <th>...</th>
            ...
        </tr>
    </thead>
    <tbody>                            
        <tr v-for="supplier in suppliers">
            <td>{{ supplier.Supplier_ID }}</td>
            <td>...</td>
            ...
        </tr>
    </tbody>
</table>

그리고 vue와 ajax:

<script>
export default {
    data() {
        return {
            suppliers: [],
        }
    },
    methods: {
        fetchSuppliers() {
            this.$http.get('http://localhost/curemodules/public/suppliers/list')
            .then(response => {
                this.suppliers = JSON.parse(response.bodyText).data;
            });
        }
    },
    created() {
        this.fetchSuppliers();
    },
}

일단 초기화되면,DataTablesDOM을 자동으로 재분석하지 않는다.관련 FAQ:

Q. DOM/jQuery를 사용하여 테이블에 행을 추가하지만, 다시 그리면 행이 제거된다.

A. 여기서 문제는 DataTables가 당신의 DOM 구조 조작에 대해 모른다는 것이다. 즉, 당신이 새로운 행을 추가했다는 것을 모르고, 다시 그리면 알 수 없는 행이 제거된다.DataTable에서 정보를 추가, 편집 또는 삭제하려면 DataTables API(특히 , 및 행 추가, 편집 및 삭제 방법)를 사용해야 한다.

그러나 현재 인스턴스를 다시 초기화하기 전에 해당 인스턴스를 제거하도록 호출할 수 있다.핵심은 부에가 구(舊)의 DOM을 플러시할 수 있도록 재초기화를 늦추는 것이다.DataTables이것은 감시자로부터 가장 잘된 것이다.suppliers그래서DataTables변수가 업데이트되면 재초기화가 자동으로 수행됨fetchSuppliers().

mounted() {
  this.dt = $(this.$refs.suppliersTable).DataTable();
  this.fetchSuppliers();
},
watch: {
  suppliers(val) {
    this.dt.destroy();
    this.$nextTick(() => {
      this.dt = $(this.$refs.suppliersTable).DataTable()
    });
  }
},

데모를 하다

나는 이것이 좀 늦은 답변이라는 것을 알지만 나는 오늘 이 문제에 직면했고 이 문제에 대한 나의 유일한 해결책은setTimeout기능을 발휘하다다음을 사용하여 데이터를 가져온 후axios그때 나는 약간의 지연을 설정했다.init자료표이 일은 v-for works를 중심으로 하면 괜찮다.

내 코드를 보려면 아래를 참조하십시오.

GetDepartmentList(){
           axios.get('department')
                .then((response) => {

                    this.departmentList = response.data;
                    // this.dataTable.rows.add(response.data).draw();
                    setTimeout(() => $('#department-data-table').DataTable(), 1000);

                })
                .catch((error) => {
                    if (error.response.status == 401) {
                        alert('User session has expired. Please login again.');
                        location.replace("/login");
                    }
                });
        },

또한 당신은 사용할 수 있다..rows.add()vue의 v-for를 사용하지 않고 표에 행 데이터를 그리려는 경우 기능한다.문서를 참조하십시오.

Vuejs에서 Axios를 사용할 수 있으며, 위 내용을 확인하십시오.

<template>
    <div class="danhsach">
      <h2>{{title}}</h2>
        <table class="table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Password</th>
                <th>Age</th>
              </tr>
            </thead>
            <tbody>
                <tr v-for='data in datas'>
                  <td>{{data.id}}</td>
                  <td>{{data.name}}</td>
                  <td>{{data.password}}</td>
                  <td>{{data.age}}</td>
                </tr>
                 
            </tbody>
        </table>
    </div>
 </template>
 <script>
  export default{
      data(){
        return {
          title:"Tile Lists",
          datas:[]
        }
      },
      created:function(){
        this.danhsach_user();
      },
      methods:{
          danhsach_user(){
           this.axios.get('https://599f807effe73c0011b9fcc5.mockapi.io/api/user').then((response)=>{
             this.datas=response.data;
            });
          }
      }
  }
 
 
 </script>
 

참조URL: https://stackoverflow.com/questions/51469984/vuejs-and-datatables-table-empty-when-using-v-for-to-fill-data

반응형