How do I call a method on a component residing in a Vue instance?
There are several questions like this one on SO but they all seem to have answers that are either deprecated, under-explained or contain answers that are concluded with "but it's recommended you don't do this..."
So I thought by providing a specific use case scenario with a current version of Vue I could glean insight into Vue "best practice" when it comes to calling methods on reusable components (or if this in itself is an anti-pattern).
Scenario: Create a reusable Vue component that represents a table that updates its data based on an API url passed at creation. Upon certain events outside the Vue instance (for example the window loses and regains focus etc), the data should update.
The table template creates from columns
and rows
Arrays.
The reusable, live table component:
Vue.component('live-table', {
props: ['url'],
data: function () {
return {
rows: [],
columns: []
}
},
created () {
this.setTable();
},
methods: {
setTable () {
axios
.get(this.url, {timeout: 1000})
.then(
response => {
this.rows = response.data.rows;
this.columns = response.data.columns;
}
)
.catch(error => (console.log(error)));
},
},
template: `
<table>
<thead>
<tr>
<th v-for="col in columns">
{{col}}
</th>
</tr>
</thead>
<tbody>
<tr v-for="row in rows">
<td v-for="col in columns" v-html="row[col]"></td>
</tr>
</tbody>
</table>`
});
Which would be used in the <body>
like this:
<div id="app">
<live-table url="/api/my_demo_data"></live-table>
</div>
Where the #app
instance is:
var app = new Vue({
el: '#app'
})
Adding this code sets up the table correctly with the data from the API. The setTable
method in the 'live-table' component would update the data from the API.
How do I call the setTable
method in the live-table components that would exist in the #app Vue instance?
Or, am I misusing/misunderstanding the use-cases of Vue components? If so, what is the best way to reuse components like the above to maintain the DRY principle, and be able to refresh the data in the tables?