【发布时间】:2020-07-04 12:00:54
【问题描述】:
我想用我的数据库中的数据填充我的 bootstrap-vue 表。我正在使用 vuex 来尝试实现这一点;但是,由于某种原因,bootstrap-vue 表没有获取数据。我检查了 Vuex 开发工具:
我将 console.log('Getters: ' + this.$store.getters.allEmployees); 添加到我的组件中,以查看检索到的内容,它只将 Getters: 输出到控制台。
为了进一步解决这个问题,我硬编码:[{"id":1,"name":"Jane Smith","email":"jane@smith.com","job_title":"Lead"},{"id":2,"name":"John Smith","email":"john@smith.com","job_title":"Installer"}] 到 employees 状态,现在数据被加载到表中。
Vuex 模块 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 组件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>
【问题讨论】:
-
您的
fetchAllEmployees操作不是composable。拥有returnAxios 承诺,即return axios.get(... -
另外,忘记使用
items,因为您已经将allEmployeesgetter 映射到allEmployees计算属性。只需使用:items="allEmployees" -
@Phil 我需要一些时间来浏览你给我的链接,并会回复,希望有一些工作代码:-D
-
让它工作。我现在明白了。我还有很多东西要学习 vuejs 和 vuex。
标签: vue.js vue-component vuex bootstrap-vue