I would like to populate my bootstrap-vue table with data from my database. I am using vuex to attempt to achieve this; however, the bootstrap-vue table isn't getting the data for some reason. I checked Vuex dev tools:
I added console.log('Getters: ' + this.$store.getters.allEmployees);
to my component to see what that retrieves and it only outputs Getters: to the console.
To further troubleshoot this, I hardcoded: [{"id":1,"name":"Jane Smith","email":"jane@smith.com","job_title":"Lead"},{"id":2,"name":"John Smith","email":"john@smith.com","job_title":"Installer"}]
into the employees
state and now the data gets loaded into the table.
Vuex module employees.js
const state = {
employees: [],
employeesStatus: null,
};
const getters = {
allEmployees: state => {
return state.employees;
},
};
const actions = {
fetchAllEmployees({commit, state}) {
commit('SET_EMPLOYEES_STATUS', 'loading');
axios.get('/api/employees')
.then(res => {
commit('SET_EMPLOYEES', res.data);
//console.log(state.employees);
commit('SET_EMPLOYEES_STATUS', 'success');
})
.catch(error => {
commit('SET_EMPLOYEES_STATUS', 'error');
});
},
};
const mutations = {
SET_EMPLOYEES(state, employees) {
state.employees = employees;
},
SET_EMPLOYEES_STATUS(state, status) {
state.employeesStatus = status;
}
};
export default {
state, getters, actions, mutations,
};
VueJS component EmployeeDataTable.vue:
<template>
<div class="overflow-auto pb-3" style="background: white; ">
<b-card
header="Employees"
header-tag="header"
>
<b-pagination
v-model="currentPage"
:total-rows="rows"
:per-page="perPage"
aria-controls="my-table"
></b-pagination>
<p class="mt-3">Current Page: {{ currentPage }}</p>
<b-table
id="employee-table"
ref="employee-table"
:items="items"
:per-page="perPage"
:current-page="currentPage"
small
></b-table>
</b-card>
</div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
name: "EmployeeDataTable",
data() {
return {
perPage: 3,
currentPage: 1,
items: [],
}
},
computed: {
...mapGetters(['allEmployees']),
rows() {
return this.items.length
}
},
methods: {
getEmployees() {
this.$store.dispatch('fetchAllEmployees').then(() => {
this.items = this.$store.getters.allEmployees;
console.log('Getters: ' + this.$store.getters.allEmployees); //<-Returns Getters:
});
//this.items = this.$store.getters.allEmployees;
}
},
mounted() {
this.getEmployees();
}
}
</script>