Imagine having the following HTML code:
<div id="app">
<h2>List of Items</h2>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items">
<td>${item.name}$</td>
<td>${item.price}$</td>
<td>${item.category}$</td>
</tr>
</tbody>
</table>
</div>
Let's create a Vue script like this:
var app = new Vue({
delimiters: ['${', '}$'],
el: '#app',
data: {
//I want to replace this hard-coded list with array fetched from API
items: [
{ name: "Keyboard", price: 44, category: 'Accessories'},
{ name: "Mouse", price: 20, category: 'Accessories'},
{ name: "Monitor", price: 399, category: 'Accessories'},
{ name: "Dell XPS", price: 599, category: 'Laptop'},
{ name: "MacBook Pro", price: 899, category: 'Laptop'},
{ name: "Pencil Box", price: 6, category: 'Stationary'},
{ name: "Pen", price: 2, category: 'Stationary'},
{ name: "USB Cable", price: 7, category: 'Accessories'},
{ name: "Eraser", price: 2, category: 'Stationary'},
{ name: "Highlighter", price: 5, category: 'Stationary'}
]
},
});
How can one make an AJAX request to fetch the items data and update the Vue component once the response is received?
Using something similar to this might seem intuitive, but it doesn't quite work:
let items;
function fetchData() {
var ajaxSendRequest = $.ajax({
url: '{{ path('get_items') }}',
type: 'GET',
dataType: 'json'
});
ajaxSendRequest.done(function (data) {
//assign the fetched data to the items variable
items = data;
}).fail(function (textStatus, errorThrown) {
});
}
//you can then use it in the Vue component
If you're unfamiliar with this process, or if the above method doesn't work as expected, what would be the correct approach to achieving the same result? (fetching data from an API and rendering it)