2👍
I recommend moving the data provision out of the table component itself. You may create a wrapper component which loads the table in a default state, fetches the data and updates the table on complete.
The table should otherwise be pretty dumb and not care about much else than rendering the data its given.
If you need a managed way to do this have a look at vuex, which also supports async actions.
Edit: I’ve attached a simple example. It should be pretty straightforward to translate to your setup.
HTML
<div id="app">
<my-container></my-container>
</div>
<script type="text/template" id="my-table-template">
<div>
<b-table
:sort-by.sync="sortBy"
:sort-desc.sync="sortDesc"
:items="items"
:fields="fields"
>
</b-table>
</div>
</script>
<script type="text/template" id="my-container-template">
<my-table :items="items"></my-table>
</script>
JavaScript
Vue.component('my-table', {
template: document.getElementById('my-table-template'),
data() {
return {
sortBy: 'age',
sortDesc: false,
fields: [
{ key: 'last_name', sortable: true },
{ key: 'first_name', sortable: true },
{ key: 'age', sortable: true },
{ key: 'isActive', sortable: false }
]
}
},
props: {
items: Array
}
})
Vue.component('my-container', {
template: document.getElementById('my-container-template'),
data() {
return {
items: []
}
},
created() {
// of course, there could be other events that would cause a data refresh
this.fetchData()
},
methods: {
fetchData() {
// you should use your real request instead of a timeout here
setTimeout(() => {
this.items = [
{ isActive: true, age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
{ isActive: false, age: 21, first_name: 'Larsen', last_name: 'Shaw' },
{ isActive: false, age: 89, first_name: 'Geneva', last_name: 'Wilson' },
{ isActive: true, age: 38, first_name: 'Jami', last_name: 'Carney' }
]
}, 1000)
}
}
})
const app = new Vue({
el: '#app'
})
As I said, it’s a good idea to separate responsibility in your app broadly into components responsible for fetching and providing data (container components) and components that just render any data they are given, without any side-effects (presentational components).
You can think of container components’ role as context providers – just consider how in the example above you can have more than one table (or varied other components) use the same data.