To update data of a Vue.js instance from a jQuery Ajax call, you can use Vue’s reactivity system to update the data once the Ajax call is successful.
We can follow the following steps:
- Make sure we have jQuery included in our project.
If not, we can include it via CDN or install it using npm.
- Create a Vue instance and define the data we want to update:
<div id="app">
<p>Data from AJAX call: {{ ajaxData }}</p>
</div>
var app = new Vue({
el: '#app',
data: {
ajaxData: ''
}
});
- Make an Ajax call using jQuery. Once the data is fetched successfully, update the Vue instance’s data:
$.ajax({
url: 'your/api/endpoint',
method: 'GET',
success: function(response) {
// Update Vue instance's data
app.ajaxData = response.data;
},
error: function(xhr, status, error) {
// Handle errors
console.error(error);
}
});
Replace 'your/api/endpoint'
with the actual URL of our API endpoint. In the success
callback function, response.data
should be replaced with the actual data structure returned by our API.
This way, when the Ajax call is successful, Vue’s reactivity system automatically updates the ajaxData
property in the Vue instance, and the changes will be reflected in our Vue component’s template.