vue.jsのdatatable-vueを使ってdjango apiからデータを表示する方法
django の設定 ページネーション
view.py
from rest_framework import generics, pagination, response
class StandardResultsSetPagination(pagination.PageNumberPagination):
page_size = 10
def get_paginated_response(self, data):
return response.Response({
'next': self.get_next_link(),
'previous': self.get_previous_link(),
'count': self.page.paginator.count, # 全件数
'total_pages': self.page.paginator.num_pages,
'current_page': self.page.number,
'results': data,
'page_size': self.page_size,
'range_first': (self.page.number * self.page_size) - (self.page_size) + 1,
'range_last': min((self.page.number * self.page_size), self.page.paginator.count),
})
Vueの設定
$ vue create datatable-vue
$ cd datatable-vue
npm run serve -- --port 3000
vue add vuetify
npm install --save axios vue-axios
<template>
<div class="">
<h1 style="text-align: center;">Datatable with drf</h1>
<v-data-table
:page="page"
:pageCount="numberOfPages"
:headers="headers" //ヘッダーの設定
:items="results" //ヘッダーに入れる中身 主に[ ] arrayで設定する
:options.sync="options"
:server-items-length="totalItems"
:loading="loading"
class="elevation-1"
>
</v-data-table>
</div>
</template>
import axios from "axios";
export default {
name: "DatatableComponent",
data() {
return {
page: 1,
totalItems: 0,
numberOfPages: 0,
results: [],
loading: true,
options: {},
headers: [
{ text: "xxxxxx", value: "yyyyyy" },
{ text: "qqqqq", value: "zzzzzz" },
{ text: "ddddd", value: "ffffffff" },
{ text: "kkkkk", value: "bbbbb" },
],
};
},
watch: {
options: {
handler() {
this.readDataFromAPI();
},
},
deep: true,
},
methods: {
readDataFromAPI() {
this.loading = true;
const { page } = this.options;
console.log("Page Number ", page);
let pageNumber = page;
axios
.get(
"http://127.0.0.1:8000/api/?page=" + pageNumber
)
.then((response) => {
this.loading = false;
const values = Object.values(response.data.results); # resultsはdjangoで設定したresultsに一致
console.log(values); # response.data.resultsがobjectで提供されているため、arrayに変換する
values.forEach((value) => {
const item = {
A: value.yyyyy,
B: value.zzzzz,
C: value.fffff,
D: value.bbbbb
};
this.results.push(item)
});
this.numberOfPages = response.data.total_pages; #djangoの設定値
this.totalItems = response.data.count #djangoの設定値
});
},
},
mounted() {
this.readDataFromAPI();
},
};
参考
現在コメントはありません