[英]How to use datatables.js in Vue.js2 project?
我想在我的 Laravel + Vue.js 項目中創建一個反應式數據表。 我正在使用datatables.js
庫來顯示我的數據。 當我進行 API 調用以從 db API 獲取數據時,我返回一個數組,因此我想將該數組填充到datatable
中。 但它的工作很奇怪?
這是 API 調用:
methods: {
getUsers() {
axios.get('/api/users')
.then(response => {
if(response.status === 200) {
this.users = response.data.users;
console.log(this.users);
}
})
.catch(error => {
console.error(error);
});
}
},
mounted() {
$('#users-datatable-responsive').DataTable();
this.getUsers();
}
這就是我在數據表中填充數據的datatable
<tr v-for="user in users">
<td>@{{ user.fullname }}</td>
<td>@{{ user.phone }}</td>
<td>@{{ user.email }}</td>
</tr>
數據表的搜索和其他功能不起作用。 解決方法是什么?
編輯:
mounted() {
let table = $('#users-datatable-responsive').DataTable({
language: this.dataTableOptions
});
this.getUsers();
table.rows().invalidate().draw();
}
這種方法對我不起作用。
如果它是一個簡單的表格,您可以使用 vue 文檔https://v2.vuejs.org/v2/examples/grid-component.html中的這個網格表格組件
我無法讓 Terry 的回答起作用,但經過一番玩耍后發現,在渲染之前破壞表格,然后在下一個滴答時重建表格確實有效。
...
methods: {
drawDT() {
$("#dt").DataTable().draw();
},
async refreshData() {
this.isLoading = true;
$("#dt").DataTable().destroy();
try {
let data = await fetchData();
this.users = data.slice(0, getRandomInt(1, data.length));
await this.$nextTick(this.drawDT);
} catch (err) {
console.error(err);
} finally {
this.isLoading = false;
}
}
},
...
根據我的評論,有兩個問題導致您看到的問題:
table.rows().invalidate().draw();
this.users
來呈現正確的標記。 使用Vue.nextTick()
調用“重置”表的邏輯。要解決這個問題,您可以在您的應用程序/組件中調用一個自定義方法來處理表格的強制刷新,即:
methods: {
getUsers() {
axios.get('/api/users')
.then(response => {
if(response.status === 200) {
// Populate VueJS data store with received data
this.users = response.data.users;
// Call a method that manually refreshes table
this.forceRefreshUserDataTable();
}
})
.catch(error => {
console.error(error);
});
}
},
mounted() {
this.usersDataTable = $('#users-datatable-responsive').DataTable();
this.getUsers();
},
methods: {
forceRefreshUserDataTable() {
Vue.nextTick(function () {
this.usersDataTable.rows().invalidate().draw();
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.