Let's say I have this html:
<div id="app">
<h2>List of Products</h2>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr v-for="product in products">
<td>${product.name}$</td>
<td>${product.price}$</td>
<td>${product.category}$</td>
</tr>
</tbody>
</table>
</div>
And a Vue script like this:
var app = new Vue({
delimiters: ['${', '}$'],
el: '#app',
data: {
//instead of this hardcoded result I'd like to get this array after sending a request
products: [
{ 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 do I send a request with AJAX to get the products object list and pass it on to Vue to render it after the result comes back from the request?
I would've imagined something like this, but this does not work:
let products;
function getHello() {
var ajaxSendRequest = $.ajax({
url: '{{ path('get_products') }}',
type: 'GET',
dataType: 'json'
});
ajaxSendRequest.done(function (data) {
//set the products variable to data that comes from response
products = data;
}).fail(function (textStatus, errorThrown) {
});
}
//after this use it in vue
I do not have much experience with stuff like this, so if this cannot be done, what is the right way to accomplish the same thing? (get data from api and then render it)