programing

Vuejs Ajax 콜 및 데이터 테이블

goodsources 2022. 8. 21. 20:01
반응형

Vuejs Ajax 콜 및 데이터 테이블

프로젝트 중 하나에 Vuejs와 dataTable을 사용하고 있습니다.Ajax에 전화를 걸어 데이터를 배열에 넣습니다.그런 다음 v-for를 사용하여 데이터 루프를 수행합니다.<tr>태그가 붙어있어요. 대부분의 경우 효과가 없어요.페이지 로드가 완료되는 즉시 테이블이 로딩됩니다.Ajax 데이터를 수신하는 데 시간이 걸립니다.출력은 다음과 같습니다.테이블에 사용 가능한 데이터가 없다고 표시됩니다.

따라서 검색 옵션이 제대로 작동하지 않습니다.잠시 후 set Timeout 함수를 사용하여 테이블을 로드하려고 했습니다.어떻게 하면 좋을까요?코드 공유:

    new Vue({
                el: '#app',
                data: {
                    entries: [],
                },
                methods:{
                    getData(){
                        var route = '/admin/temporary-enrolled-students';
                        this.$http.get(route).then((response)=>{
                            for(var i = 0; i< response.data.length;i++)
                            {
                                this.entries.push({
                                    scId: response.data[i].id,
                                    name: response.data[i].user.name,
                                    phone: response.data[i].user.phone,
                                    email: response.data[i].user.email,
                                    courseId: response.data[i].course.id,
                                    courseName: response.data[i].course.course_title,
                                    expiryDate: response.data[i].expiry_date,
                                    shares: response.data[i].number_of_shares,
                                    expired: (response.data[i].expired == 1),
                                    enrollDate: response.data[i].created_at
                                })
                            }

                        })
                    },
                },
                mounted(){
                    this.getData();
                },
            });
//data table
$(function () {
            setTimeout(()=> {          
                $("#temp-enroll").DataTable({
                    "paging": true,
                    "ordering": false,
                    "info": true,
                    "autoWidth": false
                });
            },1000);
        });

블레이드:

네, 저는 이것을 시도했고 제가 원하는 대로 일했습니다.응원해 주셔서 감사합니다.

new Vue({
                el: '#app',
                data: {
                    entries: [],
                },
                methods:{
                    getData(){
                        var route = '/admin/temporary-enrolled-students';
                        this.$http.get(route).then((response)=>{
                            for(var i = 0; i< response.data.length;i++)
                            {
                                this.entries.push({
                                    scId: response.data[i].id,
                                    name: response.data[i].user.name,
                                    ............................
                                    ......................
                                    enrollDate: response.data[i].created_at
                                })
                            }

                        }).then(()=>{
                          $("#temp-enroll").DataTable({
                            "paging": true,
                            "ordering": false,
                            "info": true,
                            "autoWidth": false
                             });
                          });
                    },
                },
                mounted(){
                    this.getData();
                },
            });

https://vuejs.org/v2/guide/computed.html#Watchers 라는 속성을 볼 수 있습니다.문서에서:

대부분의 경우 계산된 속성이 더 적합하지만 사용자 정의 워처가 필요할 수 있습니다.따라서 Vue는 워치 옵션을 통해 데이터 변경에 대한 보다 일반적인 대응 방법을 제공합니다.이 기능은 데이터 변경에 대응하여 비동기식 또는 고비용 작업을 수행할 때 가장 유용합니다.

누군가 계산한 부동산이 바람직한 방법이라고 언급했고, 저도 그렇게 권하고 싶습니다.

그 이유는 템플릿이 계산된 속성을 참조하는 즉시 Ajax 콜이 트리거되기 때문입니다.그 후 페이지는 사용 가능한 다른 요소를 렌더링하고 Ajax 콜이 반환되면 수신한 데이터를 렌더링합니다.코드에 특별한 조치는 필요하지 않습니다.

어쨌든, 이게 어떻게 보일지...

예를 들어 html에서...

 <table>
        <tr v-for="item in serverData">
            <td>{{item.name}}</td>
            <td>{{item.someOtherValue}}</td>
        </tr>
    </table>

export default {
  name: 'pets',
  data () {
    return {
    }
  },
  computed: {
    serverData: function() {
      // ajax call using axios - returns a json array []
      axios.get("http://localhost:8080/getSomeData")
      .success(function(data) {
          return data;
      };
    }
}

}

Ajax 콜에서 반환되는 성공 약속의 반환에 유의하십시오.데이터를 다른 변수에 저장할 필요가 없습니다(위의 noob coder 예시와 같이 데이터를 루프할 필요는 없습니다).서버에서 이를 실행하고 렌더링 가능한 어레이를 반환합니다.웹 서비스가 아닌 경우 원본에 호출하는 어레이를 직접 작성하여 그곳에서 데이터 조작을 수행합니다.

템플릿에서 계산된 값을 참조하는 부분은 데이터가 도착한 후에 렌더링되므로 이를 확인할 필요가 없습니다.

이게 도움이 됐으면 좋겠네요!

Vue가 폭탄이야!

    <template>
    <div class="panel panel-default tablecontainer">
        <div class="panel-heading">ChartBookin Import</div>
        <br>
        <div class='col-md-12'>
            <div class='col-md-3'></div>
            <div class='col-md-3'>
                <div class="panel panel-default">

                    <div class="panel-body">
                        <commitChart :width="150"
                                     :height="150"></commitChart>
                    </div>

                </div>
            </div>

            <div class='col-md-3'>
                <div class="panel panel-default">

                    <div class="panel-body">
                        <InboxMessage :width="150"
                                     :height="150"></InboxMessage>
                    </div>

                </div>
            </div>
        </div>
        <div class="panel-body">
            <div class='col-md-3'>
                <label> by Account </label>
                <select v-model="teamId" class="form-control" rows="3">
                    <option VALUE="" disabled> CHOISIR UN TEAM</option>
                    <option v-for="option in options" v-bind:value="option.id">{{option.name}}</option>
                </select>
            </div>
            <div class='col-md-3'>
                <label> by Date</label>
                <div class="form-group">

                    <input type="text" class="form-control" name="daterange"
                           value="01/01/2017-01/31/2017"/>
                </div>
            </div>
            <div class='col-md-5'></div>
            <div class='col-md-1'>
                <label>Records</label>
                <div class="form-group">

                    <select v-model="elementsPerPage" class="form-control">

                        <option v-for="option in filtre" v-bind:value="option">
                            {{ option }}
                        </option>
                    </select>
                </div>
            </div>

            <div id="sixthTable">

                <table class="table-bordered table-striped table-bordered table-hover">
                    <thead>
                    <tr>

                        <th v-for=" (key,value) in rows[0]" v-on:click="sortTable(value)">{{value}}
                            <div class="arrow" v-if="value == sortColumn"
                                 v-bind:class="[ascending ? 'arrow_up' : 'arrow_down']"></div>
                        </th>
                        <th>Actions</th>
                    </tr>
                    </thead>
                    <tbody>

                    <tr v-if=" rows.length > 0" v-for="row in rows">
                        <td v-for="(key, value) in row">{{ key }}</td>
                        <td>
                            <a :href="'/stat_booking_import/' + row.Id">
                                <span class="glyphicon glyphicon-eye-open"></span>
                            </a>

                        </td>
                    </tr>
                    <tr v-else> No Result Founded</tr>
                    </tbody>

                </table>
                <div class="pagination">


                    <div id="paginatebutton">
                        <a href="#">&laquo;</a>
                        <a class="" v-for="i in num_pages()"
                           v-bind:class="[i == currentPage ? 'active' : '']"
                           v-on:click="change_page(i)">{{i}}
                        </a>
                        <a href="#">&raquo;</a>
                    </div>

                    <div class="col-md-12" id="paginatetexte">
                        <p v-if="pages > (elementsPerPage*currentPage) ">
                            Showing 1 to {{elementsPerPage * currentPage }} of {{ pages }} records
                        </p>
                        <p v-else>
                            Showing 1 to {{pages}} of {{ pages }} records
                        </p>
                    </div>

                </div>
            </div>

        </div>
    </div>


</template>


<script>
    import Vue from 'vue';
    import axios from 'axios';
    import CommitChart from './Mail';
    import InboxMessage from './Inbox';


    export default {
        components: {
            CommitChart,
            InboxMessage

        },
        data() {
            return {
                filtre: [10, 25, 50, 100],
                option: 0,
                options: [],
                currentPage: 1,
                elementsPerPage: 10,
                pages: 0,
                ascending: false,
                sortColumn: '',
                startdate: null,
                enddate: null,
                options: [],
                teamId: null,
                columns: [],
                messages: [],
                date: 0,
                rows: {},
            }
        },

        created() {
            this.getData();
            this.getTeams();
            this.getMailInbox();

        },
        mounted() {
            let vm = this;
            $(document).ready(function () {
                $('input[name="daterange"]').daterangepicker({
                    ranges: {
                        'Today': [moment(), moment()],
                        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                        'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                        'This Month': [moment().startOf('month'), moment().endOf('month')]
                    },
                    locale: {
                        format: 'YYYY-MM-DD'
                    },
                });

                $('.applyBtn').click(function () {
                    vm.startdate = $("input[name=daterangepicker_start]").val();
                    vm.enddate = $("input[name=daterangepicker_end]").val();
                    vm.getData();


                });
                $('input[name="daterange"]').on('apply.daterangepicker', function (ev, picker) {
                    vm.startdate = $("input[name=daterangepicker_start]").val();
                    vm.enddate = $("input[name=daterangepicker_end]").val();
                    vm.getData();
                });

            });
        },
        watch: {
            date: function () {
                this.getData();
            },
            teamId: function () {
                this.getData();
            },
            elementsPerPage: function () {
                this.getData();
            }


        },
        methods: {

            getData() {

                axios.get(`/admin/stat_booking_import.json/` + this.startdate + `/` + this.teamId + `/` + this.enddate + `/` + this.elementsPerPage + `?page=` + this.currentPage)
                    .then(response => {
                        this.rows = response.data.elements.data;
                        this.columns = Object.keys(this.rows[0]);
                        this.pages = response.data.elements.total_element;
                    })
                    .catch(e => {
                        this.errors.push(e)
                    })

            },
            getTeams() {
                axios.get('/admin/team.json')
                    .then(response => {
                        this.options = response.data.data;
                        this.errors = [];

                    })
                    .catch(e => {
                        e.message = "aucun resultat trouvé essayer de choisir une autre date";
                        this.errors.push(e)
                    })
            },
            getMailInbox() {
                axios.get(`/mailstorage.json`)
                    .then(response => {
                        this.messages = response.data.data;
                        console.log(this.messages);

                    })
                    .catch(e => {
                        this.errors.push(e)
                    });
            },

            sortTable(col) {
                if (this.sortColumn === col) {
                    this.ascending = !this.ascending;
                } else {
                    this.ascending = true;
                    this.sortColumn = col;
                }

                var ascending = this.ascending;

                this.rows.sort(function (a, b) {
                    if (a[col] > b[col]) {
                        return ascending ? 1 : -1
                    } else if (a[col] < b[col]) {
                        return ascending ? -1 : 1
                    }
                    return 0;
                })
            },
            num_pages() {

                return Math.ceil(this.pages / this.elementsPerPage);
            },
            get_rows() {
                var start = (this.currentPage - 1) * this.elementsPerPage;
                var end = start + this.elementsPerPage;
                return this.rows.slice(start, end);
            },
            change_page(page) {
                this.currentPage = page;
                this.getData();
            }
        },

    }


</script>
<style type="text/css">
    table {
        width: 100%;
    }

    table td {
        text-align: center;
    }

    table td {
        text-align: center;
        padding: 8px;

    }

    table td:last-child {
        border-right: none;
    }

    .pagination {
        display: inline-block;
    }

    .pagination a {
        color: #3097D1;
        float: left;
        padding: 8px 16px;
        text-decoration: none;
        transition: background-color .3s;
        border: 1px solid #ddd;
    }

    .pagination a.active {
        background-color: #3097D1;
        color: white;
        border: 1px solid #3097D1;
    }

    .arrow_down {
        background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB8AAAAaCAYAAABPY4eKAAAAAXNSR0IArs4c6QAAAvlJREFUSA29Vk1PGlEUHQaiiewslpUJiyYs2yb9AyRuJGm7c0VJoFXSX9A0sSZ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AAwpJREFUSA21Vt1PUmEYP4dvkQ8JFMwtBRocWAkDbiqXrUWXzU1rrTt0bdVqXbb1tbW16C9IBUSmm27cODdneoXjputa6069qwuW6IIBIdLvdaF4OAcOiGeDc87zPs/vd57P96WpFq7p6enbGo1mjKZpeTabjU1MTCRagGnOZHFxcXxtbe1XKpUq7+zslJeXl//Mz8+Hy+Uy3RxSE9qTk5M3otFooVQqgef4Wl9f343FYoEmoISrxuNxFX5f9vb2jhn/PxUKhfLS0tIPfFifUESRUMV8Pv/M6XReRm5rTGQyGeXxeGxYe1ezeBpBOBx2rKysbO7v79d4Wy3Y2Nj4GQqFbgnhaugxwiuGJx99Pp9FLBbXxYTXvTqd7v3MzIy6riIWGxJnMpl7AwMD14xGYyMsSq1WUyQdUqn0eSPlusQIsbGrq+vl4OCgvhFQZd1utyv1en0gEolcqsi47nWJlUrlG5fLZVcoFFy2nDKSDpIWlUoVTCQSEk4lCHmJMZ2GTCbTiMVikfIZ88l7enoos9l8dXt7+z6fDicxSJUokqDX6xXcl2wCROoc0vQCWL3sNfLOSdzR0fHY4XC4tVotl40gmVwup9xuN4OQv+UyqCFGH9rg7SOGYVRcBs3IEG4J0nVnamrqOtvuBDGGgQg9+wHFcVEi4a0LNkbdd6TrPKo8ODc311mteIIYjT/a398/jK+s1jnVM0kXoufCFvq0GuiIGEVgQIhfoygM1QrteEa9dAL7ITiYCt4RMabOK5AyKKzKWtvupLcRciu8D5J0EuDDPyT/Snd39yh6VtY2NhYQSR9G79Ds7OxdskRjEyAufvb7/cPoO5Z6e1+xtVKrq6vfcFzyi/A3ZrPZ3GdNSlwgo5ekE4X2RIQGf2C1WlufFE0GBeGWYQ8YERWLxQtnUVB830MKLZfL9RHir8lkssCn2G751tZWEWe03zTKm15YWPiEiXXTYDB0Ig/t7yd8PRws4EicwWHxO4jHD8/C5HiTTqd1BwcHFozKU89origB+y/kmzgYpgOBQP4fGmUiZmJ+WNgAAAAASUVORK5CYII=')
    }

    .arrow {
        float: right;
        width: 12px;
        height: 15px;
        background-repeat: no-repeat;
        background-size: contain;
        background-position-y: bottom;
    }

    .number {
        display: inline-block;
        padding: 4px 10px;
        margin: 0px 5px;
        cursor: pointer;

    }

    .number:hover,
    .number.active {
        background-color: #3097D1;
        border-color: #3097D1;
    }

    #paginatetexte {
        padding-top: 6%;

import Vue from 'vue'


new Vue({
    el: '#statistique',
    render: h => h(require('./StatBookingImport.vue'))
});
<style type="text/css">
    table {
        width: 100%;
    }

    table td {
        text-align: center;
    }

    table td {
        text-align: center;
        padding: 8px;

    }

    table td:last-child {
        border-right: none;
    }

    .pagination {
        display: inline-block;
    }

    .pagination a {
        color: #3097D1;
        float: left;
        padding: 8px 16px;
        text-decoration: none;
        transition: background-color .3s;
        border: 1px solid #ddd;
    }

    .pagination a.active {
        background-color: #3097D1;
        color: white;
        border: 1px solid #3097D1;
    }

    .arrow_down {
        background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB8AAAAaCAYAAABPY4eKAAAAAXNSR0IArs4c6QAAAvlJREFUSA29Vk1PGlEUHQaiiewslpUJiyYs2yb9AyRuJGm7c0VJoFXSX9A0sSZN04ULF12YEBQDhMCuSZOm1FhTiLY2Rky0QPlQBLRUsICoIN/0PCsGyox26NC3eTNn3r3n3TvnvvsE1PkwGo3yUqkkEQqFgw2Mz7lWqwng7ztN06mxsTEv8U0Aam5u7r5EInkplUol/f391wAJCc7nEAgE9Uwmkzo4OPiJMa1Wq6cFs7Ozt0H6RqlUDmJXfPIx+qrX69Ti4mIyHA5r6Wq1egND+j+IyW6QAUoul18XiUTDNHaSyGazKcZtdgk8wqhUKh9o/OMvsVgsfHJy0iWqVrcQNRUMBnd6enqc9MjISAmRP3e73T9al3XnbWNjIw2+KY1Gc3imsNHR0YV4PP5+d3e32h3K316TySQFoX2WyWR2glzIO5fLTSD6IElLNwbqnFpbWyO/96lCoai0cZjN5kfYQAYi5H34fL6cxWIZbya9iJyAhULBHAqFVlMpfsV/fHxMeb3er+Vy+V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i47nWJlUrlG5fLZVcoFFy2nDKSDpIWlUoVTCQSEk4lCHmJMZ2GTCbTiMVikfIZ88l7enoos9l8dXt7+z6fDicxSJUokqDX6xXcl2wCROoc0vQCWL3sNfLOSdzR0fHY4XC4tVotl40gmVwup9xuN4OQv+UyqCFGH9rg7SOGYVRcBs3IEG4J0nVnamrqOtvuBDGGgQg9+wHFcVEi4a0LNkbdd6TrPKo8ODc311mteIIYjT/a398/jK+s1jnVM0kXoufCFvq0GuiIGEVgQIhfoygM1QrteEa9dAL7ITiYCt4RMabOK5AyKKzKWtvupLcRciu8D5J0EuDDPyT/Snd39yh6VtY2NhYQSR9G79Ds7OxdskRjEyAufvb7/cPoO5Z6e1+xtVKrq6vfcFzyi/A3ZrPZ3GdNSlwgo5ekE4X2RIQGf2C1WlufFE0GBeGWYQ8YERWLxQtnUVB830MKLZfL9RHir8lkssCn2G751tZWEWe03zTKm15YWPiEiXXTYDB0Ig/t7yd8PRws4EicwWHxO4jHD8/C5HiTTqd1BwcHFozKU89origB+y/kmzgYpgOBQP4fGmUiZmJ+WNgAAAAASUVORK5CYII=')
    }

    .arrow {
        float: right;
        width: 12px;
        height: 15px;
        background-repeat: no-repeat;
        background-size: contain;
        background-position-y: bottom;
    }

    .number {
        display: inline-block;
        padding: 4px 10px;
        margin: 0px 5px;
        cursor: pointer;

    }

    .number:hover,
    .number.active {
        background-color: #3097D1;
        border-color: #3097D1;
    }

    #paginatetexte {
        padding-top: 6%;
    }

    #paginatebutton {
        border-radius: 1px;
    }

    .tablecontainer {

        margin-right: 2%;
        margin-left: 2%;
    }

    .mailinbox {
        margin-left: 1%;
    }

</style>
<template>
    <div class="panel panel-default tablecontainer">
        <div class="panel-heading">ChartBookin Import</div>
        <br>
        <div class='col-md-12'>
            <div class='col-md-3'></div>
            <div class='col-md-3'>
                <div class="panel panel-default">

                    <div class="panel-body">
                        <commitChart :width="150"
                                     :height="150"></commitChart>
                    </div>

                </div>
            </div>

            <div class='col-md-3'>
                <div class="panel panel-default">

                    <div class="panel-body">
                        <InboxMessage :width="150"
                                     :height="150"></InboxMessage>
                    </div>

                </div>
            </div>
        </div>
        <div class="panel-body">
            <div class='col-md-3'>
                <label> by Account </label>
                <select v-model="teamId" class="form-control" rows="3">
                    <option VALUE="" disabled> CHOISIR UN TEAM</option>
                    <option v-for="option in options" v-bind:value="option.id">{{option.name}}</option>
                </select>
            </div>
            <div class='col-md-3'>
                <label> by Date</label>
                <div class="form-group">

                    <input type="text" class="form-control" name="daterange"
                           value="01/01/2017-01/31/2017"/>
                </div>
            </div>
            <div class='col-md-5'></div>
            <div class='col-md-1'>
                <label>Records</label>
                <div class="form-group">

                    <select v-model="elementsPerPage" class="form-control">

                        <option v-for="option in filtre" v-bind:value="option">
                            {{ option }}
                        </option>
                    </select>
                </div>
            </div>

            <div id="sixthTable">

                <table class="table-bordered table-striped table-bordered table-hover">
                    <thead>
                    <tr>

                        <th v-for=" (key,value) in rows[0]" v-on:click="sortTable(value)">{{value}}
                            <div class="arrow" v-if="value == sortColumn"
                                 v-bind:class="[ascending ? 'arrow_up' : 'arrow_down']"></div>
                        </th>
                        <th>Actions</th>
                    </tr>
                    </thead>
                    <tbody>

                    <tr v-if=" rows.length > 0" v-for="row in rows">
                        <td v-for="(key, value) in row">{{ key }}</td>
                        <td>
                            <a :href="'/stat_booking_import/' + row.Id">
                                <span class="glyphicon glyphicon-eye-open"></span>
                            </a>

                        </td>
                    </tr>
                    <tr v-else> No Result Founded</tr>
                    </tbody>

                </table>
                <div class="pagination">


                    <div id="paginatebutton">
                        <a href="#">&laquo;</a>
                        <a class="" v-for="i in num_pages()"
                           v-bind:class="[i == currentPage ? 'active' : '']"
                           v-on:click="change_page(i)">{{i}}
                        </a>
                        <a href="#">&raquo;</a>
                    </div>

                    <div class="col-md-12" id="paginatetexte">
                        <p v-if="pages > (elementsPerPage*currentPage) ">
                            Showing 1 to {{elementsPerPage * currentPage }} of {{ pages }} records
                        </p>
                        <p v-else>
                            Showing 1 to {{pages}} of {{ pages }} records
                        </p>
                    </div>

                </div>
            </div>

        </div>
    </div>


</template>


<script>
    import Vue from 'vue';
    import axios from 'axios';
    import CommitChart from './Mail';
    import InboxMessage from './Inbox';


    export default {
        components: {
            CommitChart,
            InboxMessage

        },
        data() {
            return {
                filtre: [10, 25, 50, 100],
                option: 0,
                options: [],
                currentPage: 1,
                elementsPerPage: 10,
                pages: 0,
                ascending: false,
                sortColumn: '',
                startdate: null,
                enddate: null,
                options: [],
                teamId: null,
                columns: [],
                messages: [],
                date: 0,
                rows: {},
            }
        },

        created() {
            this.getData();
            this.getTeams();
            this.getMailInbox();

        },
        mounted() {
            let vm = this;
            $(document).ready(function () {
                $('input[name="daterange"]').daterangepicker({
                    ranges: {
                        'Today': [moment(), moment()],
                        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                        'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                        'This Month': [moment().startOf('month'), moment().endOf('month')]
                    },
                    locale: {
                        format: 'YYYY-MM-DD'
                    },
                });

                $('.applyBtn').click(function () {
                    vm.startdate = $("input[name=daterangepicker_start]").val();
                    vm.enddate = $("input[name=daterangepicker_end]").val();
                    vm.getData();


                });
                $('input[name="daterange"]').on('apply.daterangepicker', function (ev, picker) {
                    vm.startdate = $("input[name=daterangepicker_start]").val();
                    vm.enddate = $("input[name=daterangepicker_end]").val();
                    vm.getData();
                });

            });
        },
        watch: {
            date: function () {
                this.getData();
            },
            teamId: function () {
                this.getData();
            },
            elementsPerPage: function () {
                this.getData();
            }


        },
        methods: {

            getData() {

                axios.get(`/admin/stat_booking_import.json/` + this.startdate + `/` + this.teamId + `/` + this.enddate + `/` + this.elementsPerPage + `?page=` + this.currentPage)
                    .then(response => {
                        this.rows = response.data.elements.data;
                        this.columns = Object.keys(this.rows[0]);
                        this.pages = response.data.elements.total_element;
                    })
                    .catch(e => {
                        this.errors.push(e)
                    })

            },
            getTeams() {
                axios.get('/admin/team.json')
                    .then(response => {
                        this.options = response.data.data;
                        this.errors = [];

                    })
                    .catch(e => {
                        e.message = "aucun resultat trouvé essayer de choisir une autre date";
                        this.errors.push(e)
                    })
            },
            getMailInbox() {
                axios.get(`/mailstorage.json`)
                    .then(response => {
                        this.messages = response.data.data;
                        console.log(this.messages);

                    })
                    .catch(e => {
                        this.errors.push(e)
                    });
            },

            sortTable(col) {
                if (this.sortColumn === col) {
                    this.ascending = !this.ascending;
                } else {
                    this.ascending = true;
                    this.sortColumn = col;
                }

                var ascending = this.ascending;

                this.rows.sort(function (a, b) {
                    if (a[col] > b[col]) {
                        return ascending ? 1 : -1
                    } else if (a[col] < b[col]) {
                        return ascending ? -1 : 1
                    }
                    return 0;
                })
            },
            num_pages() {

                return Math.ceil(this.pages / this.elementsPerPage);
            },
            get_rows() {
                var start = (this.currentPage - 1) * this.elementsPerPage;
                var end = start + this.elementsPerPage;
                return this.rows.slice(start, end);
            },
            change_page(page) {
                this.currentPage = page;
                this.getData();
            }
        },

    }


</script>

    }

    #paginatebutton {
        border-radius: 1px;
    }

    .tablecontainer {

        margin-right: 2%;
        margin-left: 2%;
    }

    .mailinbox {
        margin-left: 1%;
    }

</style>

언급URL : https://stackoverflow.com/questions/42176857/vuejs-ajax-call-and-datatable

반응형