Show remaining API data on b-table through pagination - vue.js

I'm trying to hit all the data from API using axios in Nuxt, but it seems only shows 10 data each page, so if there's actually 15 data which I expect to hit, it has to show 2 page (page 1 with 10 data, page 2 with the remaining 5 data). I had no idea why does it only want to show every 10 data
per page.
How to show the remaining data in next page? Here's what I've been doing so far
<script>
// eslint-disable-next-line no-unused-vars
import { getAllProvinces } from '~/api/delivery'
export default {
data() {
return {
filter: null,
filterOn: [],
perPage: 10,
currentPage: 1,
rows: 0,
items: [],
fields: [
{
key: 'id',
sortable: true,
label: 'ID',
class: 'truncate',
},
{
key: 'uploadReference',
sortable: true,
label: 'Upload Reference',
class: 'truncate',
},
{
key: 'requestId',
sortable: true,
label: 'Request ID',
class: 'truncate',
},
{
key: 'storeCode',
sortable: true,
label: 'Store Code',
class: 'truncate',
},
{
key: 'branchCode',
sortable: true,
label: 'Branch Code',
class: 'truncate',
},
{
key: 'b2bId',
sortable: true,
label: 'B2B ID',
class: 'truncate',
},
{
key: 'request',
sortable: true,
label: 'Request',
class: 'truncate',
},
{
key: 'response',
sortable: true,
label: 'Response',
class: 'truncate',
},
{
key: 'createDate',
sortable: true,
label: 'Create Date',
class: 'truncate',
},
{
key: 'errorClassification',
sortable: true,
label: 'Error Classification',
class: 'truncate',
},
],
}
},
watch: {
currentPage: {
handler(value) {
this.getAllStock()
},
},
},
created() {
this.getAllStock()
},
methods: {
getAllStock() {
this.$axios
.get(
'axioslink' +
this.currentPage +
'&status=1'
)
.then((res) => {
// eslint-disable-next-line no-console
console.log(res.data)
this.items = res.data.stocks
this.allStock = res.data
this.rows = res.data.totalDocuments
// eslint-disable-next-line no-console
})
this.rows = this.items.length
},
onFiltered(filteredItems) {
this.rows = filteredItems.length
this.currentPage = 1
},
},
}
</script>
<div class="text-center">
<b-table
id="my-table"
:per-page="perPage"
:current-page="currentPage"
striped
small
hover
dark
responsive
show-empty
:items="items"
:fields="fields"
:filter="filter"
:filter-included-fields="filterOn"
#filtered="onFiltered"
>
<template v-slot:cell()="data">
<span v-b-tooltip.hover :title="data.value">{{
data.value
}}</span>
</template>
</b-table>
</div>
</template>
<div class="overflow-auto">
<b-card-footer class="py-4 d-flex justify-content-end">
<b-pagination
:total-rows="rows"
:per-page="perPage"
aria-controls="my-table"
#change="currentPage = $event"
></b-pagination>
</b-card-footer>
</div>
Thanks and have a great day

new Vue({
el: "#menu",
data: () => ({
filter: null,
filterOn: [],
perPage: 10,
currentPage: 1,
rows: 0,
items: [],
fields: [{
key: 'id',
sortable: true,
label: 'ID',
class: 'truncate',
},
{
key: 'uploadReference',
sortable: true,
label: 'Upload Reference',
class: 'truncate',
},
{
key: 'requestId',
sortable: true,
label: 'Request ID',
class: 'truncate',
},
{
key: 'storeCode',
sortable: true,
label: 'Store Code',
class: 'truncate',
},
{
key: 'branchCode',
sortable: true,
label: 'Branch Code',
class: 'truncate',
},
{
key: 'b2bId',
sortable: true,
label: 'B2B ID',
class: 'truncate',
},
{
key: 'request',
sortable: true,
label: 'Request',
class: 'truncate',
},
{
key: 'response',
sortable: true,
label: 'Response',
class: 'truncate',
},
{
key: 'createDate',
sortable: true,
label: 'Create Date',
class: 'truncate',
},
{
key: 'errorClassification',
sortable: true,
label: 'Error Classification',
class: 'truncate',
},
],
}),
methods: {
getAllStock() {
this.items = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }, { id: 7 }, { id: 8 }, { id: 8 }, { id: 10 }, { id: 11 }, { id: 12 }, ]
// this.allStock = res.data
this.rows = this.items.length
},
onFiltered(filteredItems) {
this.rows = filteredItems.length
this.currentPage = 1
},
},
created() {
this.getAllStock()
},
});
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-vue/2.18.1/bootstrap-vue.min.css" />
<script src="https://unpkg.com/vue#2.6.12/dist/vue.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-vue/2.18.1/bootstrap-vue.min.js"></script>
<div id="menu">
<b-table id="my-table" :per-page="perPage" :current-page="currentPage" striped small hover dark responsive show-empty :items="items" :fields="fields" :filter="filter" :filter-included-fields="filterOn" #filtered="onFiltered">
</b-table>
<b-pagination v-model="currentPage" :total-rows="rows" :per-page="perPage" aria-controls="my-table"></b-pagination>
</div>

Related

Cannot read properties of undefined on formatter, but data is showing fine

I have a bootstrap table that shows a list of appliances. I am importing my data with Axios and for this specific table I am outputting data from two database tables, so I have one object which is called applianceReferences which stores another object called activeAppliances.
Not sure if it is relevant for this question, but just so you know.
Before talking about the problem, let me just post the whole code and below I will talk about the section that is giving me issues.
<template>
<b-container class="my-2">
<b-card v-if="showTable" class="ml-4 mr-4">
<b-table
search-placeholder="search"
:filter-included-fields="fields.map(f => f.key)"
include-filter
:items="applianceReferences"
:fields="fields"
/>
</b-card>
</b-container>
</template>
<script>
import {applianceService} from "#/services/appliance";
import CommonCollapsible from "#/components/common/CommonCollapsible";
import moment from 'moment';
export default {
components: { CommonCollapsible, CommonTable },
props: {
ownerId: String,
ownerType: String,
showDocuments: Boolean,
goToAppliances: "",
importAppliances: ""
},
data() {
return {
applianceReferences: [],
showTable: true
}
},
computed: {
fields() {
return [
{
key: 'referenceName',
label: this.$t('referenceName'),
sortable: true
},
{
key: 'activeAppliance.type',
label: this.$t('type'),
sortable: true,
},
{
key: 'activeAppliance.brandName',
label: this.$t('brand'),
sortable: true
},
{
key: 'activeAppliance.purchaseDate',
label: this.$t('purchaseDate'),
sortable: true,
template: {type: 'date', format: 'L'}
},
{
key: 'activeAppliance.warrantyDuration',
label: this.$t('warrantyDuration'),
sortable: true,
formatter: (warrantyDuration, applianceId, appliance) =>
this.$n(warrantyDuration) + ' ' +
this.$t(appliance.activeAppliance.warrantyDurationType ?
`model.appliance.warrantyDurationTypes.${appliance.activeAppliance.warrantyDurationType}` :
''
).toLocaleLowerCase(this.$i18n.locale),
sortByFormatted: (warrantyDuration, applianceId, appliance) =>
appliance.activeAppliance.warrantyDurationType === 'YEARS' ? warrantyDuration * 12 : warrantyDuration
},
{
key: 'activeAppliance.purchaseAmount',
label: this.$t('amount'),
sortable: true,
template: {
type: 'number', format: {minimumFractionDigits: '2', maximumFractionDigits: '2'},
foot: sum
}
},
{
key: 'actions',
template: {
type: 'actions',
head: [
{
text: 'overviewOfAppliances',
icon: 'fas fa-fw fa-arrow-right',
action: this.createAppliance
},
{
icon: 'fas fa-fw fa-file-excel',
action: this.importAppliance,
tooltip: this.$t('importAppliances'),
}
],
cell: [
{
icon: 'fa-trash',
variant: 'outline-danger',
action: this.remove
},
]
}
}
]
},
},
methods: {
load() {
Object.assign(this.$data, this.$options.data.apply(this));
this.applianceReferences = null;
applianceService.listApplianceReferences(this.ownerId).then(({data: applianceReferences}) => {
this.applianceReferences = applianceReferences;
this.applianceReferences.forEach( reference => {
applianceService.listAppliances(reference.id).then(result => {
this.$set(reference, 'appliances', result.data);
this.$set(reference, 'activeAppliance', result.data.find(appliance => appliance.active))
this.loaded = true
})
})
}).catch(error => {
console.error(error);
})
},
createAppliance(){
this.goToAppliances()
},
importAppliance(){
this.importAppliances()
},
},
watch: {
ownerId: {
immediate: true,
handler: 'load'
}
},
}
</script>
Okay, so the error occurs in this specific property:
{
key: 'activeAppliance.warrantyDuration',
label: this.$t('warrantyDuration'),
sortable: true,
formatter: (warrantyDuration, applianceId, appliance) =>
this.$n(warrantyDuration) + ' ' +
this.$t(appliance.activeAppliance.warrantyDurationType ?
`model.appliance.warrantyDurationTypes.${appliance.activeAppliance.warrantyDurationType}` :
''
).toLocaleLowerCase(this.$i18n.locale),
sortByFormatted: (warrantyDuration, applianceId, appliance) =>
appliance.activeAppliance.warrantyDurationType === 'YEARS' ? warrantyDuration * 12 : warrantyDuration
},
What I am basically doing here is combining two values from the object: warrantyDuration and warrantyDurationType and putting them in one single row in my bootstrap table.
The problem is that this is giving me an error: Cannot read properties of undefined (reading 'warrantyDurationType'
Yet the data actually outputs normally.
So what exactly does it want me to do?
I tried wrapping a v-if around the table to make sure that the application checks if the data exist before outputting it, but this does not solve the issue.
<div v-if="applianceReferences && applianceReferences.activeAppliance">
<b-card v-if="showTable" class="ml-4 mr-4">
<common-table
search-placeholder="search"
:filter-included-fields="fields.map(f => f.key)"
include-filter
:items="applianceReferences"
:fields="fields"
/>
</b-card>
</div>
Last, just to give you a full overview, my array looks like this:
Any ideas?

bootstrap vue table field label value is not showing

bootstrap vue table field label value is not showing.
fields: [
{ key: "selected", sortable: false, test: true },
{ key: 'id', label: "Number", sortable: true },
{ key: "employee", label: "Driver", sortable: false },
{ key: "vehicle", sortable: false },
{ key: "type", sortable: false },
{ key: "city", sortable: false },
{ key: "total_bilties", sortable: false },
{ key: "quantity", sortable: false },
{ key: "fare", sortable: false },
{ key: "labour", sortable: false },
{ key: "adv", sortable: false },
{ key: this.$t("action"), sortable: false }
],
output
it's not showing the Number in ID & Driver in the employee column.
It should work as per the official documentation, I just created a sample demo for the reference. Please have a look and try to find the root cause of the issue.
new Vue({
el: '#app',
data: {
items: [
{ id: 1, employee: 'Alpha', vehicle: 'Vehicle A' },
{ id: 2, employee: 'Beta', vehicle: 'Vehicle B' },
{ id: 3, employee: 'Gamma', vehicle: 'Vehicle C' },
{ id: 4, employee: 'Omega', vehicle: 'Vehicle D' }
],
fields: [
{ key: 'id', label: 'Number', sortable: true },
{ key: 'employee', label: 'Driver', sortable: false },
{ key: 'vehicle', sortable: false }
]
}
})
<!-- Load Vue -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue#latest/dist/bootstrap-vue.min.css" />
<!-- Load the following for BootstrapVueIcons support -->
<script src="https://unpkg.com/bootstrap-vue#latest/dist/bootstrap-vue.min.js"></script>
<div id="app">
<b-table :items="items" :fields="fields">
</b-table>
</div>

Vue Good Table how to access data in Selected Row Actions

I'm trying to use the checkbox in vue-good-table to select rows, then a button in the selected row action slow to perform a function on the selected rows. How can I access the data?
https://xaksis.github.io/vue-good-table/guide/advanced/checkbox-table.html#selected-row-action-slot
This doesn't work:
<vue-good-table
#on-selected-rows-change="selectAll"
:columns="columns2"
id="shift.id"
:ref="shift.id"
:rows="orderedPlacedUsers(shift)"
:select-options="{
enabled: true,
selectOnCheckboxOnly: true,
}"
>
<div slot="selected-row-actions">
<button class="btn btn__small btn__flat" #click="lockAll(shift)">Lock All <i class="ml-2 fas fa-lock-alt"></i></button>
</div>
</div>
</vue-good-table>
Then
data() {
return {
columns2: [
{
label: '',
field: 'extras',
tdClass: 'text-center',
sortable: false,
},
{
label: 'Name',
field: 'fullName',
},
{
label: 'Signed Up',
field: 'created',
sortable: false,
},
{
label: 'Job',
field: 'requestedJob.title',
tdClass: 'text-center',
},
{
label: '',
field: 'notes',
sortable: false,
tdClass: 'text-center',
},
{
label: '',
field: 'reservations',
tdClass: 'text-center',
tdClass: 'text-center',
sortable: false,
},
{
label: '',
field: 'delete',
tdClass: 'text-center',
sortable: false,
},
]
}
}
methods: {
lockAll(shift) {
console.log(shift.id)
console.log(this.$refs[shift.id].selectedRows)
},
orderedPlacedUsers (shift) {
function compare(a, b) {
if (a.firstName < b.firstName)
return -1;
if (a.firstName > b.firstName)
return 1;
return 0;
}
return this.filteredPlacedUsers.sort(compare).filter(user => {
return user.shift == shift.id && user.day == shift.day
});
},
}
The shift is "shift in eventShifts"... here's what that looks like:
{"day":"2021-08-27","endTime":null,"payrollComplete":true,"startTime":"14:00","event":"Los Bukis","id":"dvaBm5wQXMXvVCGBSK8e","exportedCont":{"seconds":1631208172,"nanoseconds":886000000},"collapse":false,"position":{"title":null},"selectedStaff":null,"eventId":"CGHMVzcKPnNLsmRxoeVj","exportedEmp":{"seconds":1631208185,"nanoseconds":622000000},"name":"Line Cook","staff":"50"}
Thank you!
To access the vue-good-table via this.$refs you need to add :ref property into vue-good-table.
<vue-good-table
:id="shift.id"
:ref="shift.id"
>
</vue-good-table>
But there is another thing to be considered, it says here that
When used on elements/components with v-for, the registered reference
will be an Array containing DOM nodes or component instances.
In your case, probably vue-good-table is used on an element/component with v-for. So, you can access it via this.$refs[shift.id][0]. Finally, you can print the selectedRows using console.log(this.$refs[shift.id][0].selectedRows)

How to use pagination in BootstrapVue

I have created a b-table that stores all the data from the API that has been hit from Swagger UI, but since the data has a lot of characters in string, My questions are how to make the data in each row be hovered on click to show the real data from API that hasn't been truncated? I've tried using v-b-tooltip but it seems doesn't work. If I may, I also wanted to know more about how to make the b-pagination works to load another data as I navigate page further.
Here's my current code:
<template>
<base-header>
<template>
<b-card body>
<b-card-header class="border-0">
<h3 class="mb-0">Stock List</h3>
</b-card-header>
<template>
<div class="text-center">
<b-table responsive dark striped hover:true :items="items" :fields="fields">
<template #cell()="data">
<span v-b-tooltip.hover :title="data.value">
{{ data.value }}
</span>
</template>
</b-table>
</div>
</template>
<div class="overflow-auto">
<b-card-footer class="py-4 d-flex justify-content-end">
<b-pagination
v-model="currentPage"
:total-rows="rows"
:per-page="perPage"
aria-controls="my-table"
></b-pagination>
</b-card-footer>
</div>
</b-card>
</template>
</base-header>
</template>
and then here's the script
<script>
// eslint-disable-next-line no-unused-vars
import { getAllProvinces } from '~/api/delivery'
export default {
// components: {
// },
data() {
return {
perPage: 10,
currentPage: 1,
allStock: 0,
text: '',
rows: 100,
// ubah rows dan perPage biar paginationnya ada value
items: [],
fields: [
{
key: 'id',
sortable: true,
label: 'ID',
class: 'truncate',
},
{
key: 'requestId',
sortable: true,
label: 'Request ID',
class: 'truncate',
},
{
key: 'storeCode',
sortable: true,
label: 'Store Code',
class: 'truncate',
},
{
key: 'branchCode',
sortable: true,
label: 'Branch Code',
class: 'truncate',
},
{
key: 'b2bId',
sortable: true,
label: 'B2B ID',
class: 'truncate',
},
{
key: 'request',
sortable: true,
label: 'Request',
class: 'truncate',
},
{
key: 'response',
sortable: true,
label: 'Response',
class: 'truncate',
},
{
key: 'createDate',
sortable: true,
label: 'Create Date',
class: 'truncate',
},
{
key: 'errorClassification',
sortable: true,
label: 'Error Classification',
class: 'truncate',
},
],
}
},
mounted() {
this.getAllStock()
},
methods: {
getAllStock() {
this.$axios
.get(
'API Link'
)
.then((res) => {
// eslint-disable-next-line no-console
console.log(res.data)
this.items = res.data.stocks
this.allStock = res.data
// eslint-disable-next-line no-console
// console.log('cek res stock:', JSON.stringify(res.data))
})
},
computed: {
rows() {
return this.items.length
},
},
},
}
</script>
<style>
.truncate {
max-width: 200px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
The documentation is pretty self-explanatory: https://bootstrap-vue.org/docs/components/pagination
But I added several comments on the code below (the template is therefore invalid!)
<template>
<div class="overflow-auto">
<b-pagination
v-model="currentPage" // this is the most important, bind the currentPage state to the pagination component, two-way data binding
:total-rows="rows" // display how much total data there is
:per-page="perPage" // this one will tell how much data per page you want to display
aria-controls="my-table" // this is for a11y
></b-pagination>
<p class="mt-3">Current Page: {{ currentPage }}</p>
<b-table
id="my-table"
:items="items" // where to look for the data
:per-page="perPage"
:current-page="currentPage" // re-use the current value of the pagination component
small
></b-table>
</div>
</template>
<script>
export default {
data() {
return {
perPage: 3,
currentPage: 1,
items: [ // your items, that you may replace with a new array if fetching an API in between each pagination page change
{ id: 1, first_name: 'Fred', last_name: 'Flintstone' },
{ id: 2, first_name: 'Wilma', last_name: 'Flintstone' },
{ id: 3, first_name: 'Barney', last_name: 'Rubble' },
{ id: 4, first_name: 'Betty', last_name: 'Rubble' },
{ id: 5, first_name: 'Pebbles', last_name: 'Flintstone' },
{ id: 6, first_name: 'Bamm Bamm', last_name: 'Rubble' },
{ id: 7, first_name: 'The Great', last_name: 'Gazzoo' },
{ id: 8, first_name: 'Rockhead', last_name: 'Slate' },
{ id: 9, first_name: 'Pearl', last_name: 'Slaghoople' }
]
}
},
computed: {
rows() {
return this.items.length
}
}
}
</script>
Of course, depending of the amount of data, you may want to watch for the currentPage value and make a new API call, fetching the next elements.
This totally depends on the API implementation but it's essentially passing 2 rather than 1 in URL's query params or somewhere into the headers.
As you can see in Github's API here: https://docs.github.com/en/rest/reference/repos#list-repositories-for-the-authenticated-user--parameters
Theirs is awaiting for a page and per_page params, hence the values of our VueJS state that we will send a new API call with.

Vuejs2- How to do an inline alignment of a radio button in vue-form-generator?

Iam using "vue-form-generator" plugin for dynamic loading of form fields. Among the fields, I am using "radio-button" for the "gender" field. Options are displayed in one below the other but I want the option should be displayed in the "inline" style
How to align the radio button option in the same row(inline)?
Here is my code: addMember.vue
<template>
<div class="panel-body">
<vue-form-generator :schema="schema" :model="model" :options="formOptions"></vue-form-generator>
<input type="submit" value="Submit">
</div>
</template>
<script>
import Vue from 'vue'
import VueFormGenerator from "vue-form-generator";
import "vue-form-generator/dist/vfg.css";
Vue.use(VueFormGenerator);
export default {
data: () => ({
model: {
building: "",
unitCategory: "",
unit: "",
fullName: "",
gender: "",
},
schema: {
groups: [{
fields: [{
type: "select",
inputType: "text",
label: "Building",
model: "building",
required: true,
styleClasses:'col-md-6',
values: [
{ id: "", name: 'Select Building' },
{ id: 'A', name: 'Block-A'},
{ id: 'B', name: 'Block-B'},
],
selectOptions: {
hideNoneSelectedText: true,
}
}]
},{
fields: [{
type: "select",
inputType: "text",
label: "Unit Category",
model: "unitCategory",
required: true,
styleClasses:'col-md-3',
values: [
{ id: "", name: 'Select Unit Category' },
],
selectOptions: {
hideNoneSelectedText: true,
}
},{
type: "select",
inputType: "text",
label: "Unit",
model: "unit",
required: true,
styleClasses:'col-md-3',
values: [
{ id: "", name: 'Select Unit' },
],
selectOptions: {
hideNoneSelectedText: true,
}
}]
},{
fields: [{
type: "input",
inputType: "text",
label: "Full Name",
model: "fullName",
placeholder: "Enter Full Name",
required: true,
styleClasses:'col-md-3'
},
{
type: "radios",
label: "Gender",
model: "gender",
values: [
"Male",
"Female",
"Other"
],
styleClasses:'col-md-3'
}]
}]
},
formOptions: {
validateAfterLoad: true,
validateAfterChanged: true
}
}),
}
</script>
You can add custom css to your radio input
{
type: "radios",
label: "Gender",
model: "gender",
values: [
"Male",
"Female",
"Other"
],
styleClasses:'col-md-3 display-inline'
}
and in your css
.display-inline label {
display: inline !important;
}
var vm = new Vue({
el: "#app",
components: {
"vue-form-generator": VueFormGenerator.component
},
data() {
return {
model: {
},
schema: {
fields: [{
type: "radios",
label: "Select your gender",
model: "friend",
values: [
"Male",
"Female",
"Others"
],
styleClasses: "display-inline"
}]
},
formOptions: {
validateAfterLoad: true,
validateAfterChanged: true
}
};
}
});
.display-inline label {
display: inline !important;
}
<link href="https://cdn.jsdelivr.net/npm/vue-form-generator#2.2.2/dist/vfg.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/vue-form-generator#2.2.2/dist/vfg.min.js"></script>
<script src="https://unpkg.com/vue#2.2.1/dist/vue.min.js"></script>
<h1 class="text-center">Demo of vue-form-generator</h1>
<div class="container" id="app">
<div class="panel panel-default">
<div class="panel-heading">Form</div>
<div class="panel-body">
<vue-form-generator :schema="schema" :model="model" :options="formOptions"></vue-form-generator>
</div>
</div>
</div>