Having recently started using Vue, I'm looking to implement an AJAX call each time my component is rendered. I have a Vue component named "test-table" and I want to retrieve the contents through an AJAX request. There are multiple tables like this, and I keep track of the active one using v-if/v-else-if conditions.
Currently, I have a workaround: in the component's template, I invoke a computed property named getData using {{ getData }}
which triggers the Ajax call but only returns an empty string. I wish to switch to a proper solution but I'm unsure how to go about it.
Here is a snippet of my TypeScript code:
Vue.component("test-table", {
props: ["request"],
data () {
return {
tableData: [] as Array<TableClass>,
}
},
template: `{{ getData() }} DO SOME STUFF WITH tableData...`,
computed: {
getData() : string {
get("./foo.php", this.request, true).then(
data => this.tableData = data.map(element => new TableClass(data))
)
return "";
}
}
}
HTML:
<test-table v-if="testcounter === 1" :request="stuff..."></test-table>
<test-table v-else-if="testcounter === 2" :request="other stuff..."></test-table>
...
The get method is asynchronous and sends a GET request to the server with request data. The last parameter specifies that the method should expect a JSON response, similar to jQuery's getJSON method.
The "created" hook does not work! It only runs once when the component is initially created. If I deactivate and reactivate it (using v-if), the method is not triggered again.
By the way, I'm using Vue 2.6.13